Seeking Optimization for Speed Bottleneck in 3D Data Processing

WindVChen: <p>Hi everyone,</p>
<p>Lately, I’ve been immersed in the realm of 3D data processing, yet I’ve encountered a significant speed bottleneck attributed to the <code>.cuda()</code> operation within my workflow.</p>
<p>To provide some context, I’m working with batches of volumetric data with a shape of (16, 8, 128, 128, 128), which need to be transferred to CUDA for subsequent deep learning processes. However, I’ve observed that the <code>.cuda()</code> operation alone can consume approximately 0.5 seconds on my device. This duration is strikingly similar to the time it takes for my neural network to complete a forward pass (~0.5 seconds) (the simplified code snippet below):</p>
<pre data-code-wrap="python"><code class="lang-python">import torch
import time

# CUDA warm up
a = torch.ones([16, 8, 128, 128, 128])
a = a.cuda()

torch.cuda.synchronize()
start = time.time()

a = torch.ones([16, 8, 128, 128, 128])
a = a.cuda()

torch.cuda.synchronize()
print(time.time() - start)
# ~0.5s in my device
</code></pre>
<p>Despite exploring various avenues for optimization, such as increasing the <code>num_workers</code> parameter, I’ve found no tangible improvements since the bottleneck isn’t directly linked to the dataset’s <code>__getitem()__</code> operation. While enabling <code>pin_memory</code> did yield some speed enhancements, the gains were marginal, barely reducing the time to approximately 0.3 seconds.</p>
<p>In an attempt to leverage the multiprocessing capabilities of PyTorch’s <code>DataLoader</code>, I experimented with pre-loading data onto the GPU within the <code>collate_fn()</code> function (the simplified code snippet below). Remarkably, this approach resulted in significantly faster processing times (~0.004 seconds) when combined with an appropriate <code>num_workers</code> setting. However, it introduced unexpected anomalies, such as all tensors within the first batch being zero-valued, followed by subsequent batches exhibiting a mix of correct and zero-valued tensors. (I have no idea why these happen)</p>
<pre data-code-wrap="python"><code class="lang-python">def collate_fn(batch, device):
    # Transfer sdf_points to cuda
    batch_sdf_points = torch.stack([item[0] for item in batch], dim=0).type(torch.float32).to(device, non_blocking=True)
    return batch_sdf_points

dataload = torch.utils.data.DataLoader(
            self.train_dataset,
            batch_size=self.batch_size,
            num_workers=self.num_workers,
            shuffle=True,
            drop_last=True,
            persistent_workers=True,
            collate_fn=partial(collate_fn, device='cuda')
            )
</code></pre>
<p>Given these challenges, I’m reaching out to seek any insights or recommendations regarding further optimizations to expedite this process. Any assistance or guidance would be immensely appreciated.</p>

nlgranger: <p>Hi,</p>
<p>You might want to use <code>non_blocking=True</code> in <code>.to(device=)</code> or <code>.cuda()</code> in conjunction with pin_memory if your are transferring multiple of these large tensors in succession. If only once I don’t think it will help. Also it will make profiling more difficult.</p>
<p>About transferring to GPU in <code>collate_fn</code>, it’s just a guess, but I’d look around possible synchronization issues. For example: what if the asynchronous memory transfer in the data worker is still going on while the tensor handle has already been transferred to the train process and the forward pass has started?</p>

WindVChen: <p>Hi Nicolas,</p>
<p>Many thanks for your help!</p>
<p>I used Pytorch-lightning in my code, and <code>non_blocking</code> seems always activated. Thus, there may be no further benefit I can get there.</p>
<blockquote>
<p>what if the asynchronous memory transfer in the data worker is still going on while the tensor handle has already been transferred to the train process and the forward pass has started?</p>
</blockquote>
<p>Ah! It sounds reasonable why I encountered those weird phenomena. Under this conjecture, the collated tensors seem to be always initialized with <code>zero values</code>.</p>
<p>Maybe I need an explicit <code>torch.cuda.synchronize()</code> at the end of <code>collate_fn()</code>. As I’m not quite familiar with cuda operations, is there any potential by-effect of doing these cuda operations in multiprocessing?</p>

nlgranger: <blockquote>
<p>is there any potential by-effect of doing these cuda operations in multiprocessing?</p>
</blockquote>
<p>I was wondering the same. To be sure, you can try to do the .cuda() on a separate cuda stream. Something in the line of:</p>
<pre><code class="lang-auto">s = torch.cuda.Stream(device=??)
with torch.cuda.stream(s):
    batch = batch.pin_memory().to(device=??, non_blocking=True)
s.synchronize()
</code></pre>