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__ requires sampler to be an instance of torch.utils.data.Sampler because it iterates the sampler to build batches per group. Passing a list, range, or DataLoader instead of a Sampler raises ValueError with the repr of the object.
Source
Thrown at pytorch_object_detection/mask_rcnn/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
- Pass a torch.utils.data.Sampler subclass instance, e.g. torch.utils.data.RandomSampler(dataset) or a custom aspect-ratio sampler
- Wrap any iterable in Sampler: class ListSampler(Sampler): def __init__(self, lst): self.lst = lst; def __iter__(self): return iter(self.lst); def __len__(self): return len(self.lst)
- Ensure the DataLoader wiring is sampler=GroupedBatchSampler(sampler, group_ids, batch_size), not batch_sampler with wrong args
Example fix
// before sampler = GroupedBatchSampler(dataset, group_ids, batch_size=4) # dataset is not a Sampler // after base = torch.utils.data.RandomSampler(dataset) sampler = GroupedBatchSampler(base, group_ids, batch_size=4)
Defensive patterns
Strategy: type-guard
Validate before calling
from torch.utils.data import Sampler assert isinstance(sampler, Sampler), 'GroupedBatchSampler requires a torch Sampler instance' gbs = GroupedBatchSampler(sampler, group_ids, batch_size)
Type guard
def is_torch_sampler(s):
from torch.utils.data import Sampler
return isinstance(s, Sampler) Try / catch
try:
gbs = GroupedBatchSampler(sampler, group_ids, batch_size)
except ValueError as e:
if 'instance of' in str(e):
sampler = torch.utils.data.RandomSampler(dataset)
gbs = GroupedBatchSampler(sampler, group_ids, batch_size)
else:
raise Prevention
- Always pass a Sampler subclass, never a raw iterable
- Remember len(group_ids) must equal len(sampler)/dataset
- Verify the DataLoader uses sampler= not batch_sampler= when composing yourself
When it happens
Trigger: Instantiating GroupedBatchSampler(batch_size=..., group_ids=...) with a plain list, range object, or dataset as sampler — commonly when using batch_sampler=GroupedBatchSampler(dataset, ...) instead of a sampler instance.
Common situations: Passing a DataLoader where a sampler is expected; confusing torch's BatchSampler composition order; using a non-torch sampler implementation.
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
- sampler should be an instance of torch.utils.data.Sampler, b
- sampler should be an instance of torch.utils.data.Sampler, b
- sampler should be an instance of torch.utils.data.Sampler, b
- sampler should be an instance of torch.utils.data.Sampler, b
- sampler should be an instance of torch.utils.data.Sampler, b
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/6d341dc6f4e1e7c0.
Report an issue: GitHub.