Getting small patches from large volumes in a random order

username: dmus
cooked: <p>I work with large 3D volumes of medical images on which data augmentations are done which take some time, so using the multiprocessing of the dataloader is a must. Suppose the following example code:</p>
<pre><code class="lang-auto">import numpy as np
import time
from torch.utils.data import DataLoader, Dataset


class ExpensiveTransform():

    def __call__(self, sample):
        print('Sleeping...')
        time.sleep(5)
        return sample

class ToPatches():

    def __call__(self, sample):
        patches = [sample['id']] * 20
        return patches

class CustomDataset(Dataset):
    def __init__(self, transform):
        self.transform = transform

    def __len__(self):
        return 10

    def __getitem__(self, idx):
        sample = np.random.rand(640, 580, 72)
        sample = {'id': idx, 'image': sample}

        if self.transform:
            for transform in self.transform:
                sample = transform(sample)

        return sample

def main():
    dataset = CustomDataset(transform=[ExpensiveTransform(), ToPatches()])

    loader = DataLoader(dataset,
                        batch_size=1,
                        num_workers=2,
                        persistent_workers=True)

    for epoch in range(10):
        for patches in loader:
            print(patches)

if __name__ == "__main__":
    main()
</code></pre>
<p>This gives as an output:</p>
<blockquote>
<p>Sleeping…<br>
Sleeping…<br>
[tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0]), tensor([0])]<br>
[tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1]), tensor([1])]<br>
Sleeping…<br>
Sleeping…<br>
[tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2]), tensor([2])]<br>
[tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3]), tensor([3])]<br>
Sleeping…<br>
Sleeping…<br>
[tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4]), tensor([4])]<br>
[tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5]), tensor([5])]<br>
Sleeping…<br>
Sleeping…</p>
</blockquote>
<p>However, as I final result I want to get batches of let’s say 4 patches and in a random order. For example</p>
<blockquote>
<p>[tensor([2]), tensor([7]), tensor([0]), tensor([1])]<br>
[tensor([5]), tensor([4]), tensor([5]), tensor([0])]</p>
</blockquote>
<p>In Tensorflow there are the .unbatch and the shuffle() methods in tf.data to achieve this. How could the same by achieved by PyTorch?</p>

username: ptrblck
cooked: <p>If you want to create patches from different inputs, you should increase the batch size and don’t repeat the <code>sample['id']</code> in <code>ToPatches()</code>.<br>
Note that the <code>_getitem__</code> method will get an index for each sample in the batch.<br>
Given your desired output it seems you want to use <code>batch_size=4</code> and <code>shuffle=True</code> in the <code>DataLoader</code>.</p>

username: dmus
cooked: <p>Thanks for our answer. I understand that this is a solution. However, the point is that the 3D volumes are big and the patches relatively small. Doing the preprocessing and augmentations on the big volumes takes some time, therefore it is very inefficient to only sample one small patch per volume.</p>
<p>I solved this by wrapper this dataset in a UnbatchDataset (similar to the .unbatch() in tensorflow) and the BufferedShuffleDataset (only in pytorch nightly, part of the 1.8 release?).</p>
<p>However, now I encounter this issue after training for several hours: RuntimeError: unable to open shared memory object &lt;/torch_37358_1335134282&gt; in read-write mode</p>
<p>Any ideas?</p>

username: ptrblck
cooked: <p>This error might be raised, if your system doesn’t have enough shared memory, so you might need to increase it.</p>