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

GroupedBatchSampler's __init__ validates that the sampler argument is an instance of torch.utils.data.Sampler. If any other object (list, iterable, None, custom class not inheriting Sampler) is passed, it raises ValueError naming the offending object. This guarantees the sampler exposes __iter__/__len__ semantics the batch sampler relies on.

Source

Thrown at pytorch_object_detection/train_coco_dataset/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 the indices in torch.utils.data.Sampler (e.g. create a subclass with __iter__/__len__) before passing it
  2. If you already have a sampler-like object, make it inherit from torch.utils.data.Sampler
  3. Check what you are passing: print(type(sampler)) and confirm it is not a list or ndarray

Example fix

// before
sampler = list(range(len(dataset)))
batch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)
// after
from torch.utils.data import Sampler
class MySampler(Sampler):
    def __init__(self, data_source):
        self.data_source = data_source
    def __iter__(self):
        return iter(range(len(self.data_source)))
    def __len__(self):
        return len(self.data_source)
batch_sampler = GroupedBatchSampler(MySampler(dataset), group_ids, batch_size)
Defensive patterns

Strategy: type-guard

Validate before calling

from torch.utils.data import Sampler
if not isinstance(sampler, Sampler):
    raise TypeError(f'expected torch.utils.data.Sampler, got {type(sampler)}')

Type guard

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

Try / catch

try:
    bs = GroupedBatchSampler(sampler, group_ids, batch_size)
except ValueError as e:
    if 'sampler should be an instance' in str(e):
        sampler = ListSampler(list(sampler))
        bs = GroupedBatchSampler(sampler, group_ids, batch_size)
    else:
        raise

Prevention

When it happens

Trigger: Calling GroupedBatchSampler(sampler, group_ids, batch_size) with a plain list, generator, Dataset, or a custom sampler class that does not subclass torch.utils.data.Sampler.

Common situations: Refactoring code that previously iterated indices directly; passing indices=list(range(len(dataset))) instead of wrapping in a Sampler; using a third-party sampler from an older torch version with a different base class.

Understand the failure class

Background: Invalid argument type errors: "must be of type string", "expected X, got Y", and ERR_INVALID_ARG_TYPE explained — this error's family across 15 libraries.

Related errors


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