Skip to main content

A PyTorch BatchSampler that produces batches from samples clustered by keys.

Project description

Clustered Batch Sampler

A PyTorch BatchSampler that produces batches from samples clustered by keys. Ensures that each batch contains only samples belonging to the same cluster, which is useful for tasks like training on images with different sizes or when samples need to be processed together based on shared properties.

Installation

pip install clustered-batch-sampler

Features

  • Cluster integrity: Guarantees each batch contains samples from only one cluster
  • Flexible keys: Use a list of explicit keys or a callable function to define clusters. Keys must be hashable. Using a callable function eagerly evaluates the whole dataset when the sampler is initialized.
  • Shuffling: Supports deterministic shuffling of both clusters and samples within clusters
  • Distributed training: Support for distributed sampling, following PyTorch's DistributedSampler
  • Drop options: Control whether to drop incomplete batches, following PyTorch's BatchSampler

Usage

Example Usage

import torch
from torch.utils.data import DataLoader, Dataset

from clustered_batch_sampler import ClusteredBatchSampler


class RandomImageDataset(Dataset):
    def __init__(self, num_samples: int):
        self.num_samples = num_samples
        self.sizes = [192, 224, 256, 288, 320]

    def __len__(self):
        return self.num_samples

    def __getitem__(self, idx):
        if idx >= self.num_samples:
            raise IndexError("Index out of range")
        size = self.sizes[idx % len(self.sizes)]
        image = torch.randn(3, size, size)
        return image


dataset = RandomImageDataset(num_samples=100)
key_fn = lambda x: x.shape[-2:]
sampler = ClusteredBatchSampler(dataset, key=key_fn, batch_size=16)
dataloader = DataLoader(dataset, batch_sampler=sampler)

for b in dataloader:
    print(b.shape)

Output:

torch.Size([16, 3, 256, 256])
torch.Size([16, 3, 192, 192])
torch.Size([16, 3, 288, 288])
torch.Size([4, 3, 256, 256])
torch.Size([16, 3, 224, 224])
torch.Size([16, 3, 320, 320])
torch.Size([4, 3, 192, 192])
torch.Size([4, 3, 320, 320])
torch.Size([4, 3, 288, 288])
torch.Size([4, 3, 224, 224])

Using Explicit Keys

keys = [key_fn(dataset[i]) for i in range(len(dataset))]
sampler = ClusteredBatchSampler(dataset, key=keys, batch_size=16)

Distributed Training

Similar to PyTorch's DistributedSampler, calling the set_epoch() method at the beginning of each epoch before creating the DataLoader iterator is necessary to make shuffling work properly across multiple epochs. Otherwise, the same ordering will be always used.

If distributed=True, either initialize the current distributed process group first or pass num_replicas and rank explicitly.

See also: https://docs.pytorch.org/docs/stable/data.html#torch.utils.data.distributed.DistributedSampler

Notes and Caveats

  • The sampler assumes a map-style dataset that supports both __len__ and indexed __getitem__ access.
  • When key is a callable, keys are computed eagerly for every dataset item during sampler initialization.
  • Keys must be hashable because they are used to group samples into clusters.
  • drop_last_samples drops incomplete batches inside each cluster.
  • drop_last_batches only affects distributed mode and controls whether whole batches are dropped or repeated to divide work evenly across replicas.
  • Shuffling is deterministic across epochs and across distributed workers when the same seed and epoch are used.

Parameters

  • dataset: PyTorch dataset with __len__ and __getitem__
  • key: Either a sequence of hashable keys (one per sample) or a callable returning a hashable key for each item
  • batch_size: Size of mini-batch
  • shuffle: Whether to shuffle batches and samples (default: True)
  • seed: Random seed for reproducibility (default: 0)
  • drop_last_samples: Drop incomplete batches within clusters (default: False)
  • drop_last_batches: Drop batches to make data evenly divisible across replicas in distributed mode (default: False)
  • distributed: Enable distributed sampling across multiple processes (default: False)
  • num_replicas: Number of processes in distributed training (optional, by default retrieved from the current initialized distributed group)
  • rank: Process rank in distributed training (optional, by default retrieved from the current initialized distributed group)

Development And Release

Install development tools:

pip install -e .[dev]

Run local preflight checks before publishing:

ruff check .
pytest -q
python -m build
twine check dist/*

GitHub Actions Workflows

  • CI workflow: .github/workflows/ci.yml
    • Runs lint, tests, package build, and twine check on push and pull requests.
  • Publish workflow: .github/workflows/publish.yml
    • Runs the same validation checks, builds package artifacts, and publishes with trusted publishing.
    • Triggers on published GitHub releases (publishes to PyPI).
    • Also supports manual dispatch for TestPyPI or PyPI.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

clustered_batch_sampler-0.1.0.tar.gz (8.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

clustered_batch_sampler-0.1.0-py3-none-any.whl (7.2 kB view details)

Uploaded Python 3

File details

Details for the file clustered_batch_sampler-0.1.0.tar.gz.

File metadata

  • Download URL: clustered_batch_sampler-0.1.0.tar.gz
  • Upload date:
  • Size: 8.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for clustered_batch_sampler-0.1.0.tar.gz
Algorithm Hash digest
SHA256 e629116f7287f868c0c525a03006d6c1069f90edf81e13c6aa0ade24f52cda72
MD5 e1fa07aadcf0cfcd079224e62e13354a
BLAKE2b-256 9a41edb197182786c7e5ecfed44ec71557817c38893e27fb20225886888e6c97

See more details on using hashes here.

Provenance

The following attestation bundles were made for clustered_batch_sampler-0.1.0.tar.gz:

Publisher: publish.yml on marcvornehm/clustered-batch-sampler

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file clustered_batch_sampler-0.1.0-py3-none-any.whl.

File metadata

File hashes

Hashes for clustered_batch_sampler-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 5f013ad8aaaa7ef4dbf3418e1e7c6140903d333d77ac71fbcc1fd1519c4c92df
MD5 93def099aca2891aac334ede8fed227d
BLAKE2b-256 08d434026889cb1371c6449aaa9c0a52bdc969b0bd3269737b4368aa0b525f84

See more details on using hashes here.

Provenance

The following attestation bundles were made for clustered_batch_sampler-0.1.0-py3-none-any.whl:

Publisher: publish.yml on marcvornehm/clustered-batch-sampler

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page