WZMIAOMIAO/deep-learning-for-image-processing · error · ValueError

sampler should be an instance of torch.utils.data.Sampler, b

Error message

sampler should be an instance of torch.utils.data.Sampler, but got sampler={}

What it means

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.

Source

Thrown at pytorch_object_detection/retinaNet/train_utils/group_by_aspect_ratio.py:39


class GroupedBatchSampler(BatchSampler):
    """
    Wraps another sampler to yield a mini-batch of indices.
    It enforces that the batch only contain elements from the same group.
    It also tries to provide mini-batches which follows an ordering which is
    as close as possible to the ordering from the original sampler.
    Arguments:
        sampler (Sampler): Base sampler.
        group_ids (list[int]): If the sampler produces indices in range [0, N),
            `group_ids` must be a list of `N` ints which contains the group id of each sample.
            The group ids must be a continuous set of integers starting from
            0, i.e. they must be in the range [0, num_groups).
        batch_size (int): Size of mini-batch.
    """
    def __init__(self, sampler, group_ids, batch_size):
        if not isinstance(sampler, Sampler):
            raise ValueError(
                "sampler should be an instance of "
                "torch.utils.data.Sampler, but got sampler={}".format(sampler)
            )
        self.sampler = sampler
        self.group_ids = group_ids
        self.batch_size = batch_size

    def __iter__(self):
        buffer_per_group = defaultdict(list)
        samples_per_group = defaultdict(list)

        num_batches = 0
        for idx in self.sampler:
            group_id = self.group_ids[idx]
            buffer_per_group[group_id].append(idx)
            samples_per_group[group_id].append(idx)
            if len(buffer_per_group[group_id]) == self.batch_size:
                yield buffer_per_group[group_id]

View on GitHub (pinned to 1ec3fe6f37)

Solutions

  1. Wrap your indices in torch.utils.data.sampler.SubsetRandomSampler or pass RandomSampler(dataset)
  2. Make the custom sampler inherit from torch.utils.data.Sampler
  3. Pass the sampler that was already constructed in the training setup (e.g. RandomSampler) rather than the dataset

Example fix

// before
GroupedBatchSampler(dataset, group_ids, batch_size)
// after
sampler = RandomSampler(dataset)
GroupedBatchSampler(sampler, group_ids, batch_size)
Defensive patterns

Strategy: type-guard

Validate before calling

from torch.utils.data import Sampler
assert isinstance(sampler, Sampler), 'pass a torch Sampler (e.g. RandomSampler)'
assert isinstance(group_ids, (list, tuple)) and len(group_ids) == len(sampler)

Type guard

def is_torch_sampler(obj) -> bool:
    from torch.utils.data import Sampler
    return isinstance(obj, Sampler)

Try / catch

try:
    grouped = GroupedBatchSampler(sampler, group_ids, batch_size)
except ValueError as e:
    print(f'Sampler invalid: {e}; wrap indices in SubsetRandomSampler')

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30). Data as JSON: /api/errors/a92a01b69af59b2b. Report an issue: GitHub.