# Dataloader for variable batch size

**URL:** <https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840>\
**Category:** Uncategorized\
**Created:** [February 20, 2018, 8:32am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840 "2018-02-20T08:32:51Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![hij](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hij/32/14113_2.png) [@hij](https://discuss.pytorch.org/u/hij)\
**Post date:** [February 20, 2018, 8:32am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/1 "2018-02-20T08:32:52Z")

</div>

Hi I am new to this and for most application I have been using the dataloader in utils.data to load in batches of images. However I am now trying to load images in different batch size. For example my first iteration loads in batch of 10, second loads in batch of 20.

Is there a way to do this easily? Thank you.

---

<div class="post-metadata">

**Author:** ![turpaultn](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/turpaultn/32/25377_2.png) [@turpaultn](https://discuss.pytorch.org/u/turpaultn)\
**Post date:** [July 30, 2018, 12:35pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/2 "2018-07-30T12:35:43Z")

</div>

Hi,  
Same problem here,  
Did you succeed to do it ?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [July 30, 2018, 12:40pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/3 "2018-07-30T12:40:21Z")

</div>

You could implement a custom `collate_fn` for your [DataLoader](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) and use it to load your batches.

---

<div class="post-metadata">

**Author:** ![justusschock](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/justusschock/32/4637_2.png) [@justusschock](https://discuss.pytorch.org/u/justusschock)\
**Post date:** [July 30, 2018, 12:40pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/4 "2018-07-30T12:40:45Z")

</div>

I think the easiest way to achieve this is to change the `batch_size` parameter of the Dataloader.

---

<div class="post-metadata">

**Author:** ![turpaultn](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/turpaultn/32/25377_2.png) [@turpaultn](https://discuss.pytorch.org/u/turpaultn)\
**Post date:** [July 30, 2018, 1:11pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/5 "2018-07-30T13:11:52Z")

</div>

Thank you very much for your answers!!  
I actually found what I wanted with the sampler in this discussion: [405015099](https://github.com/pytorch/pytorch/issues/1512#issuecomment-405015099) and changing the batch size with a batch\_size for each source (here my data\_source is the concatenation of datasets with specific batch\_size for each).  
Not very clean but seems to work.

```auto
class ClusterRandomSampler(Sampler):
    r"""Takes a dataset with cluster_indices property, cuts it into batch-sized chunks
    Drops the extra items, not fitting into exact batches
    Arguments:
        data_source (Dataset): a Dataset to sample from. Should have a cluster_indices property
        batch_size (int): a batch size that you would like to use later with Dataloader class
        shuffle (bool): whether to shuffle the data or not
    """

    def __init__ (self, data_source, batch_size=None, shuffle=True):
        self.data_source = data_source
        if batch_size is not None:
            assert self.data_source.batch_sizes is None, "do not declare batch size in sampler " \
                                                         "if data source already got one"
            self.batch_sizes = [batch_size for _ in self.data_source.cluster_indices]
        else:
            self.batch_sizes = self.data_source.batch_sizes
        self.shuffle = shuffle

    def flatten_list(self, lst):
        return [item for sublist in lst for item in sublist]

    def __iter__ (self):

        batch_lists = []
        for j, cluster_indices in enumerate(self.data_source.cluster_indices):
            batches = [
                cluster_indices[i:i + self.batch_sizes[j]] for i in range(0, len(cluster_indices), self.batch_sizes[j])
            ]
            # filter our the shorter batches
            batches = [_ for _ in batches if len(_) == self.batch_sizes[j]]
            if self.shuffle:
                random.shuffle(batches)
            batch_lists.append(batches)

            # flatten lists and shuffle the batches if necessary
        # this works on batch level
        lst = self.flatten_list(batch_lists)
        if self.shuffle:
            random.shuffle(lst)
        return iter(lst)

    def __len__ (self):
        return len(self.data_source)

```

---

<div class="post-metadata">

**Author:** ![R0dluvan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/r0dluvan/32/27150_2.png) [@R0dluvan](https://discuss.pytorch.org/u/R0dluvan)\
**Post date:** [October 11, 2020, 10:45am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/6 "2020-10-11T10:45:32Z")

</div>

I have been trying to use `collate_fn` for this purpose but haven’t figured out how, yet. Can you give any pointers? My problem right now is the sampler gives `collate_fn` 16 samples at a time, but I want the batch size to be 128. Is this possible with this approach?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [October 12, 2020, 12:24am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/7 "2020-10-12T00:24:36Z")

</div>

The `collate_fn` is used to process the batch of samples in a custom way. It doesn’t specify the batch size, which is set in the `DataLoader`.  
Could you explain your issue a bit more, i.e. are you setting a batch size of 128 in the `DataLoader` and each batch contains just 16 samples?

---

<div class="post-metadata">

**Author:** ![R0dluvan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/r0dluvan/32/27150_2.png) [@R0dluvan](https://discuss.pytorch.org/u/R0dluvan)\
**Post date:** [October 12, 2020, 6:29am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/8 "2020-10-12T06:29:10Z")

</div>

I’m trying to replicate the original StyleGAN’s batch size schedule: 128, 128, 128, 64, 32, 16 as the progressive growing is applied. I know I can recreate the DataLoader when I want to switch, but I’m working inside an extant framework that makes that a clunky change to make.

I never did figure out how to use `collate_fn` here so instead, I’m initializing my DataLoader with a `batch_size` of 16, and in my training loop I collect and concatenate these batches until I reach the actual batch size I want at any given time. This only works because all the batch sizes are divisible by 16. I tried to do this in `collate_fn` at first, I thought maybe it received a generator and I could return a different generator, but that wasn’t the case.

I’m still interested to know how `collate_fn` can be used to yield variable batch sizes, maybe it would be cleaner than my solution.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [October 12, 2020, 6:34am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/9 "2020-10-12T06:34:11Z")

</div>

You could use [this code snippet](https://discuss.pytorch.org/t/how-to-create-a-dataloader-with-variable-size-input/8278/3) to see an example.  
Note that the “variable size” is usually the temporal dimension or the spatial dimensions (e.g. images with a different resolution) not the batch size.

---

<div class="post-metadata">

**Author:** ![R0dluvan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/r0dluvan/32/27150_2.png) [@R0dluvan](https://discuss.pytorch.org/u/R0dluvan)\
**Post date:** [October 16, 2020, 7:43pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/10 "2020-10-16T19:43:54Z")

</div>

That snippet again does not modify the batch size, which is the subject of this thread.

---

<div class="post-metadata">

**Author:** ![atherfawaz](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/atherfawaz/32/31762_2.png) [@atherfawaz](https://discuss.pytorch.org/u/atherfawaz)\
**Post date:** [November 30, 2020, 7:59pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/11 "2020-11-30T19:59:25Z")

</div>

I’ve come across the same issue while trying to implement this functionality of StyleGAN using PyTorch Lightning, which I believe is like your use case. Any luck on your end in resolving this issue?

---

<div class="post-metadata">

**Author:** ![gengala](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/gengala/32/55222_2.png) [@gengala](https://discuss.pytorch.org/u/gengala)\
**Post date:** [November 27, 2022, 7:40pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/12 "2022-11-27T19:40:02Z")

</div>

Any news? How one could change the batch size of the dataloader during training?

---

<div class="post-metadata">

**Author:** ![FarzanT](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/farzant/32/31150_2.png) [@FarzanT](https://discuss.pytorch.org/u/FarzanT)\
**Post date:** [May 23, 2023, 10:23pm UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/13 "2023-05-23T22:23:15Z")

</div>

I also wish there was a way to do this, e.g. make the batch size depend on the size of the input samples in the case of variable-length input data, such as sentences, etc.

---

<div class="post-metadata">

**Author:** ![drscotthawley](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/drscotthawley/32/118_2.png) [@drscotthawley](https://discuss.pytorch.org/u/drscotthawley)\
**Post date:** [May 22, 2025, 12:40am UTC](https://discuss.pytorch.org/t/dataloader-for-variable-batch-size/13840/14 "2025-05-22T00:40:44Z")

</div>

I looks like there’s a library answer this call here: [GitHub - ancestor-mithril/bs-scheduler: A Batch Size Scheduler library compatible with PyTorch DataLoaders.](https://github.com/ancestor-mithril/bs-scheduler)
