Dataset location (RuntimeError: Caught RuntimeError in DataLoader worker process 0.)

muammar: <p>I have a custom dataset as shown below:</p>
<pre><code class="lang-auto">class MyDataset(Dataset):
    def __init__(self, X, y):

        self.X = X
        self.y = y

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

    def __getitem__(self, idx):
        return self.X[idx], self.y[idx]


training_latent_dataset = MyDataset(
    torch.cat(training_latent), torch.cat(training_labels)
)

train_latent_loader = torch.utils.data.DataLoader(
    training_latent_dataset, batch_size=batch_size, shuffle=True, **kwargs
)
</code></pre>
<p>If the tensors are already on the GPU and I try to iterate over the Dataset, I get this error:</p>
<pre><code class="lang-auto">RuntimeError: Caught RuntimeError in DataLoader worker process 0.
Original Traceback (most recent call last):
  File "/home/muammar/miniconda3/envs/py39/lib/python3.9/site-packages/torch/utils/data/_utils/worker.py", line 287, in _worker_loop
    data = fetcher.fetch(index)
  File "/home/muammar/miniconda3/envs/py39/lib/python3.9/site-packages/torch/utils/data/_utils/fetch.py", line 49, in fetch
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/home/muammar/miniconda3/envs/py39/lib/python3.9/site-packages/torch/utils/data/_utils/fetch.py", line 49, in &lt;listcomp&gt;
    data = [self.dataset[idx] for idx in possibly_batched_index]
  File "/tmp/ipykernel_356729/3661499099.py", line 11, in __getitem__
    return self.X[idx], self.y[idx]
RuntimeError: CUDA error: initialization error
CUDA kernel errors might be asynchronously reported at some other API call,so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
</code></pre>
<p>If I move the tensors from GPU to CPU when instantiating the <code>MyDataset</code> class, then everything works well:</p>
<pre><code class="lang-auto">training_latent_dataset = MyDataset(
    torch.cat(training_latent).cpu(), torch.cat(training_labels).cpu()
)

train_latent_loader = torch.utils.data.DataLoader(
    training_latent_dataset, batch_size=batch_size, shuffle=True, **kwargs
)
</code></pre>
<p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/3/c/3cac7beec3dc6fbcb794a0ef1489429bf9552e7c.png" data-download-href="https://discuss.pytorch.org/uploads/default/3cac7beec3dc6fbcb794a0ef1489429bf9552e7c" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/3/c/3cac7beec3dc6fbcb794a0ef1489429bf9552e7c_2_690x156.png" alt="image" data-base62-sha1="8EKc0HUapNmGevn2d9RVUlBQ27O" width="690" height="156" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/3/c/3cac7beec3dc6fbcb794a0ef1489429bf9552e7c_2_690x156.png, https://discuss.pytorch.org/uploads/default/optimized/3X/3/c/3cac7beec3dc6fbcb794a0ef1489429bf9552e7c_2_1035x234.png 1.5x, https://discuss.pytorch.org/uploads/default/optimized/3X/3/c/3cac7beec3dc6fbcb794a0ef1489429bf9552e7c_2_1380x312.png 2x" data-dominant-color="F3F3F3"><div class="meta"><svg class="fa d-icon d-icon-far-image svg-icon" aria-hidden="true"><use href="#far-image"></use></svg><span class="filename">image</span><span class="informations">2246×510 76.9 KB</span><svg class="fa d-icon d-icon-discourse-expand svg-icon" aria-hidden="true"><use href="#discourse-expand"></use></svg></div></a></div></p>
<p>Is that the expected behavior for the tensors to be in the CPU instead of the GPU? I could not find anything about that in the documentation.</p>

ptrblck: <p>Yes, usually you would load the data on the CPU and push it to the GPU inside the training loop in order to overlap the data loading with the actual model training.<br>
However, if you want to load CUDATensors directly, check the <a href="https://pytorch.org/docs/stable/notes/multiprocessing.html#cuda-in-multiprocessing">CUDA multiprocessing docs</a> to avoid re-creating a CUDA context, which raises your error.</p>

muammar: <p>Hi <a class="mention" href="/u/ptrblck">@ptrblck</a>, thanks for your fast reply and the link. That makes sense. I was very confused when I faced this.</p>

N_N_miko: <p>Well, since the poster’s problem has solved, I’ll not asking other solution of this. But I still have some problem, I did load my tensors to GPU in the training loop, but what it cost me was some kind of weird pulse effect, where the DataLoader’s workers are trying to put the tensor to gpu over and over again during training. When I was checking my GPU usage, it just increase a bit and then droped and back again.<br>
I don’t know how am I going to solve this problem, if you have any idea, please share to me, huge thanks to you.</p>

ptrblck: <p>I don’t understand your issue and what unexpected “pulse effect” is observed. The <code>DataLoader</code> will prefetch batches in the background if <code>num_workers&gt;0</code> is used. If you are moving these batches to the GPU inside the <code>DataLoader</code>, an increase in memory is expected.</p>

N_N_miko: <p>What I mean was the DataLoader will only push those data to GPU once a time, so when I check my GPU usage, it will increase to 78 and then decrease to 0 again and again, which slows the training process down.<br>
I’ve solved it now by just simply use another DataLoader and load all data to GPU first before the training happen, which is still kind of weird solution.<br>
Sorry I didn’t make myself clear, English is not my mother language and I’m a slow learner, haha.<br>
If you still can’t get what I mean, Here is the code that caused this: “src_data, tgt_data = batch[0].to(device), batch[1].to(device)”, I push it to the GPU inside the loop as you mentioned. I use num_workers=16 in my case, I wish it could load the data to GPU while the model is doing calculation, but it didn’t work in my case, I don’t know if I didn’t load my data in the right way.</p>