Efficiency of dataloader and collate for large array-like datasets

IngoMarquart: <p>I have been writing a custom dataset to handle my HDF5-stored tables, and I really like it as an abstraction and interface. I liked it so much I just played with the class and added some flexbility that should make sense to efficiently gather my data.</p>
<p>So me, a horrible, terrible newbie and pytorch phillistine, wrote the dataset as I would intuitively use it (even outside of training loops).</p>
<p>BUT, I found that the pyTorch dataloader handles this quite differently, and I would ask your thoughts.<br>
In particular, I am not sure if the dataloader is really efficient when used with the canonical HDF5 implementation, or what the trade-offs are. More on that below.</p>
<h1>Use case</h1>
<p>I query a HDF5 database for NLP purposes. This is simply a large array-like table, where each row of this database is a sequence of words. The reason to use HDF5 (pyTables to be exact), is that the whole corpus is large and can not fit into memory.</p>
<p>In the getitem function, I open the table (according to the internet, this is necessary for threading as HDF5 is in general not thread safe), get the data, tokenize and augment (padding to fixed length). All of this works great.</p>
<h1>My intuitive approach before looking at the dataloader</h1>
<p>The output of <code>dataset[i]</code>, that is, a single row, should be a pytorch tensor of tokens, a different tensor of dimension 1 with the sequence id, and potentially other relevant data.<br>
Let’s say the return value is a list or tuple <code>(token_tensor(1xlength), sequence_id(1)</code>.<br>
So far, so good.</p>
<p>When writing the dataset class, I thought it would make sense to allow a query of the style <code>dataset[i:k]</code>. I implemented this so that the dataset class returns, for n elements, a tuple <code>(token_tensor(nxlength), sequence_id(nx1)</code>.</p>
<p>This makes sense for two reasons. First, it’s nice to be able to use the dataset class as abstraction for pulling data and do all processing. Second, since it is querying a HDF5 file by index, it is also efficient to pull multiple entries at once, given the overhead of opening the database.</p>
<p>So in essence, I wrote a dataset class that can return both single entries, and batches.</p>
<h1>Enter dataloader</h1>
<p>Dataloader handles things differently. It always accesses a single element, and collates a batch as a tuple of single elements.<br>
That is, instead of asking for <code>n</code> items of the form <code>[i:j]</code> from the dataset, the dataloader queries the dataset <code>n</code> times to get a <code>n</code> length tuple of <code>(token_tensor(1xlength), sequence_id(1)</code>.</p>
<p>This means I have to use a custom collate function to step over elements of this tuple. And so, I am doing some operations that technically should not be necessary and I’d imagine are not efficient:</p>
<ol>
<li>List operations over tuples to collate the rows. Since I am using a table or array style data source, the data <strong>already comes</strong> in form of an array that can be turned into a tensor. Why transform it to tuples of single elements?</li>
<li>I open and close (in case of HDF5), or at least access the database many, many more times, instead of pulling a larger sample straight away. pyTables, for example, can return any coordinates of rows, exactly what the dataloader should need to create a sample.</li>
</ol>
<h1>My question</h1>
<p>I have now set things up such that the output of dataloader+collate and dataset[i:j] are the same. That is, I can either query a batch “raw” via dataset, or I can do so with a dataloader+collate function and get the same thing.</p>
<p>I am not asking “why does the dataloader work this way”.<br>
I realize that the dataloader works the way it does for flexibility. In many situations, what I am doing in the dataset makes no sense or isn’t possible. And given the structure of the operation, letting dataset (as opposed to the dataloader) return batches is clearly not the original intention. I get that. I am also conscious of the possibility that all this is a technical necessity related to threading and the like.</p>
<p>But I can’t help but feel that for many use cases, in particular those where data is queried from an array-like data source, the logic with dataloader may not be efficient for the reasons mentioned above.</p>
<p><strong>My question is therefore the following:</strong> What is correct way in pyTorch to load and sample data of this form?<br>
Online, I have almost only found tutorials where either a) the data fits into memory, in which case all of this doesn’t matter, or b) tutorials on non-array like data (like images), where it makes sense to read from single files each time c) approaches that are similar to mine, but of course have the disadvantages above.</p>
<p>Perhaps I am missing what the correct way in pyTorch is? Perhaps there are some implementations or tools that I did not find?<br>
Or maybe I am wrong, and loading single elements is not really a performance issue in the first place?</p>
<p>But if that is not true, it seems that there is something missing in the way pyTorch implements datasets, which is the use case of accessing array like databases. Of course I can write my own dataset/dataloader class to work with array like databases. But this includes doing all the threading and optimization etc, and as a newbie, I can’t hope to match the efficiency of pyTorch devs, so that seems like a bad idea.</p>
<p>Further, you may say that one should not use a HDF5 DB for text, instead loading the raw text samples as a dataset. But this makes no sense to me, because first, one can not really query sequences in raw text files except with a secondary database, and second, basic operations such as deleting non-text, segmentation, and the like, I think should not be part of the training loop, and finally, a compressed HDF5 is probably faster than loading text files anyway, especially because one can query by index?</p>
<p>I apologize if this is all wrong. I tried hard to find “efficient” and “canonical” ways to work with HDF5 files in pyTorch, and it seems that this is what people do. But that can’t really be right.</p>
<p>I’d be happy for your thoughts! Thank you!</p>

IngoMarquart: <p>Indeed I ran a timing test comparing the two. The code is as follows:</p>
<pre><code class="lang-auto">import time
start_time = time.time()

for i in range(0, dataset.nitems-200, 200):
        batch = dataset[i,i+200]
        print(i)
        print(batch[1])
        print(batch[2])

dataset.close()
print("--- %s seconds ---" % (time.time() - start_time))
</code></pre>
<p>And for the dataloader</p>
<pre><code class="lang-auto">import time
start_time = time.time()

dataloader = DataLoader(dataset, batch_size=200, shuffle=False, num_workers=16,pin_memory=False,collate_fn=text_dataset_collate)

for i, batch in enumerate(dataloader):
       print(i)
       print(batch[1])
       print(batch[2])

dataset.close()
print("--- %s seconds ---" % (time.time() - start_time))
</code></pre>
<p>Custom batching takes</p>
<pre><code class="lang-auto">--- 2.1859922409057617 seconds ---
</code></pre>
<p>The dataloader takes</p>
<pre><code class="lang-auto">--- 19.42865824699402 seconds ---
</code></pre>
<p>I know this is not quite perfect, because of printing as operation (is this significant) and also the dataset is rather small, only 200k sequences.</p>
<p>But the difference is staggering, even though the dataloader process runs on 16 threads, and the custom batching is simply a loop?<br>
For other batch sizes, differences are even larger. In particular, the dataloader hovers around 20 seconds, decreasing slightly with batch sizes, but the custom loop goes down to things like 0.05 seconds!</p>
<p>Profiling shows that the main difference are the dataloader functions, next and get_data. So it really seems that loading data step by step is inefficient</p>
<p>What am I doing wrong?</p>
<p>This can not be right</p>

IngoMarquart: <p>I have replicated the test with a more realistic task, encoding the sequences with BERT from pytorch-transformers on my CPU without any threading except num_workers in the dataloader.</p>
<p>Outcome is the same, using batching via the dataset is at least 10x faster than using a dataloader.</p>
<p>I am 100% sure  I am doing something wrong, but my dataset class is quite standard, except that I have to open and close a database file, and tokenize+pad in the getitem function, but of course that is the same whether I use dataloader or custom batches.<br>
Thoughts?</p>

SimonW: <p>In case where bulk read makes sense, you should not use <code>DataLoader</code> in the default random read style.</p>
<p>Here is a quick start on how to switch to bulk loading mode.</p>
<p>Instead, write a sampler that spits out <code>keys</code> representing batch index (e.g., range, or list of indices). For <code>DataLoader</code>, set <code>batch_size=None</code> and use <code>sampler=</code> for your new sampler. And in dataset code <code>__getitem__</code>, the input is what your custom sampler yields, so something that represents batch indices, so use that to index into your <code>hdf5</code> and return the array.</p>

IngoMarquart: <p>Ahh that makes sense. Thank you!</p>
<p>I will start a new question for batch sampling</p>

fly2mars: <pre><code>For  `DataLoader` , set  `batch_size=None`  and use  `sampler=`  for your new sampler.
</code></pre>
<p>Do you mean <code>batch_sampler=</code> instead of <code>sampler=</code> ? I learned from the doc that <code>batch_sampler=</code> yields batch of indices a time, which suits this case. Here’s the doc: <a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader" rel="nofollow noopener">https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader</a></p>
<ul>
<li>
<strong>sampler</strong>  (<a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.Sampler" rel="nofollow noopener"> <em>Sampler</em> </a> <em>,</em>  <em>optional</em> ) – defines the strategy to draw samples from the dataset. If specified,  <code>shuffle</code>  must be  <code>False</code> .</li>
<li>
<strong>batch_sampler</strong>  (<a href="https://pytorch.org/docs/stable/data.html#torch.utils.data.Sampler" rel="nofollow noopener"> <em>Sampler</em> </a> <em>,</em>  <em>optional</em> ) – like  <code>sampler</code> , but returns a batch of indices at a time. Mutually exclusive with  <code>batch_size</code> ,  <code>shuffle</code> ,  <code>sampler</code> , and  <code>drop_last</code> .</li>
</ul>

IngoMarquart: <p>I find this part slightly confusing, as there are several options.</p>
<p>My concerns are in this new thread:</p><aside class="quote quote-modified" data-post="1" data-topic="59673">
  <div class="title">
    <div class="quote-controls"></div>
    <img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ingomarquart/48/17144_2.png" class="avatar">
    <a href="https://discuss.pytorch.org/t/bulk-batch-sampling-options/59673">Bulk Batch Sampling Options</a> 
  </div>
  <blockquote>
    I am essentially looking for the best-practice for loading bulk batches of data, and I find very little definitive information in the docs or online, even though I’d imagine this is a quite common use case. 
Task description
My specific use-case has two features of import 


The data does not fit into memory but needs to be fetched from a table / array style database. However, given that it is array-like, it can be indexed very easily (or in case of a DB, queried even non-sequentially). And adja…
  </blockquote>
</aside>

<p>The issue, as I see it, is that there are in fact several ways to set up “batch sampling” in the documentation. These include setting up a custom sample function, using the pre-defined batch sampler class  <em>also as a custom sampler</em> (both cases have batch_size=None), and finally just setting this batch sampling parameter.</p>
<p>However, just setting batch size and dropout, which is said to be equivalent in the docs, clearly does not return a set of indicies to the dataset, but rather queries single indicies which are then collated.</p>
<p>I vow to try all these options on my problem today or tomorrow, and report back in detail what produces the fastest performance when reading small, medium and large batches from a HDF5 database.</p>
<p>In particular, I am unsure what is better: Using a custom batch sampler and a map style dataset, or using an iterative dataset, where the iteration is determined by a custom batch size.<br>
This is what I want to test - or find out if anyone knows…</p>

SimonW: <p>I meant <code>sampler=</code>. The approach I described is effectively turning off auto-collation in PyTorch, i.e., to make the DataLoader think that it is loading a single data sample at the time, similar to</p>
<pre><code class="lang-auto">for index in sampler:
  yield convert_to_tensor(dataset[index])
</code></pre>
<p>It is just that to achieve bulk loading, we return a range / list of indices in <code>sampler</code>, which is used to index the dataset as a single key. If <code>batch_sampler</code> is used instead, DataLoader will unpack the list yielded by the <code>batch_sampler</code> and index the dataset with the resulting keys one-by-one.</p>

SimonW: <aside class="quote no-group" data-username="IngoMarquart" data-post="7" data-topic="59569">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ingomarquart/48/17144_2.png" class="avatar"> IngoMarquart:</div>
<blockquote>
<p>Using a custom batch sampler and a map style dataset, or using an iterative dataset, where the iteration is determined by a custom batch size.</p>
</blockquote>
</aside>
<p>Yes, you are right that there are two ways:</p>
<ol>
<li>use <code>IterableDataset</code>: sampling is in dataset code, which is run in worker process.</li>
<li>use <code>batch_size=None</code> and <code>sampler=custom_sampler_that_is_really_a_batch_sampler</code>: sampling is done by a separate class, run in main process.</li>
</ol>
<p>In general, <code>IterableDataset</code> gives you finer control, because you can achieve things like data-dependent batch size / ordering. And depending on your code, having sampling logic and fetching logic in the same class may be cleaner. But since sampling is done in workers, you likely need to configure each worker to make sure they don’t load duplicate batches, or load in correlated ordering. To me, the second approach makes more sense if your sampling and fetching logic are relatively isolated, and is usually less tricky to implement.</p>
<p>Re docs: The docs could use some improvements… It was largely my fault. If I find some free time I would update it. Sorry about it.</p>

IngoMarquart: <p>Ahh now I get it with regards to batch_sampler and sampler, I thought it was the other way around. This also explains why a batch_sampler=… does not speed up the data_loader.</p>
<p>I am in the process of benchmarking all those options for my use-case.</p>