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-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.
Source
Thrown at pytorch_keypoint/HRNet/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
- 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.
Example fix
# before sampler = list(range(len(dataset))) batch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size) # ValueError # after from torch.utils.data.sampler import SubsetRandomSampler sampler = SubsetRandomSampler(list(range(len(dataset)))) batch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)
Defensive patterns
Strategy: type-guard
Validate before calling
from torch.utils.data import Sampler
assert isinstance(sampler, Sampler), f"got {type(sampler).__name__}; wrap indices in a Sampler" Type guard
from torch.utils.data import Sampler
def is_valid_sampler(obj) -> bool:
return isinstance(obj, Sampler) Try / catch
try:
batch_sampler = GroupedBatchSampler(sampler, group_ids, batch_size)
except ValueError as e:
logging.error("Bad sampler: %s — wrapping in SubsetRandomSampler", e)
batch_sampler = GroupedBatchSampler(SubsetRandomSampler(sampler), group_ids, batch_size) Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Expected target boxes to be of type Tensor, got {:}.
- 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
- return_layers are not present in model
AI-assisted analysis of WZMIAOMIAO/deep-learning-for-image-processing@1ec3fe6f37 (2026-08-30).
Data as JSON: /api/errors/7fb45c80d7aca05b.
Report an issue: GitHub.