CUDNN_STATUS_NOT_INITIALIZED error when using batch size > 1

hm2092: <p>Hi Everyone.<br>
I ran into RuntimeError: CUDNN_STATUS_NOT_INITIALIZED,  while trying a batch_size &gt; 1 for training(and also validation). My system details are:<br>
Cuda version: 9.0.176<br>
Cudnn version: 7102<br>
Pytorch version: 0.4.0<br>
GPU: GTX 1080 Ti<br>
Driver version: 390.77<br>
OS: Ubuntu 16.04</p>
<p>With a batch_size of 1, the training loop works fine. This problem arises when I increase the batch size. Detailed traceback is given below:</p>
<pre><code class="lang-auto">&lt;ipython-input-20-8f012bcb5dc5&gt; in forward(self, x)
      9 
     10     def forward(self, x):
---&gt; 11         x = self.conv3d_1(x)
     12         x = self.conv3d_2(x)
     13         x = self.conv3d_3(x)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    489             result = self._slow_forward(*input, **kwargs)
    490         else:
--&gt; 491             result = self.forward(*input, **kwargs)
    492         for hook in self._forward_hooks.values():
    493             hook_result = hook(self, input, result)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/container.py in forward(self, input)
     89     def forward(self, input):
     90         for module in self._modules.values():
---&gt; 91             input = module(input)
     92         return input
     93 

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
    489             result = self._slow_forward(*input, **kwargs)
    490         else:
--&gt; 491             result = self.forward(*input, **kwargs)
    492         for hook in self._forward_hooks.values():
    493             hook_result = hook(self, input, result)

/usr/local/lib/python3.6/dist-packages/torch/nn/modules/conv.py in forward(self, input)
    419     def forward(self, input):
    420         return F.conv3d(input, self.weight, self.bias, self.stride,
--&gt; 421                         self.padding, self.dilation, self.groups)
    422 
RuntimeError: CUDNN_STATUS_NOT_INITIALIZED
</code></pre>
<p>I realized that in this issue (<a href="https://discuss.pytorch.org/t/cudnn-status-not-initialized-when-using-cnn/16766/3?u=hm2092">CUDNN_STATUS_NOT_INITIALIZED when using cnn</a>) also, the error occured for conv1D layer and in my case, in conv3D layer.<br>
Any help would be great. Thank you in advance.</p>

hm2092: <p>I found the solution. I was using a custom collate function for dataloader and one of the variables was initialized wrong. I was copying a tensor (index wise) to another, based on the indices in the wrongly initialized variable right before the conv3d layer. So it was more like an “out of range” error or something and I was confused by the CUDNN_STATUS_NOT_INITIALIZED error statement.</p>

addisonklinke: <p><a class="mention" href="/u/hm2092">@hm2092</a> thank you for sharing your error - I think I am experiencing something very similar where the cuDNN message only happens for batch size &gt; 1. Could you explain more about how you debugged the location of the “out of range” error? My DataLoader + custom <code>collate_fn</code> is fairly straightforward and there are no issues preparing the batches</p>
<p>On a separate note, why did PyTorch only implement a <code>Dataset</code> class for COCO, but not a <code>DataLoader</code> and/or collate function? It seems this is standard enough that plenty of other people are using it…</p>
<pre><code class="lang-auto">from spellchecker import SpellChecker
import torch
import torch.nn as nn
from torchvision import transforms
from torchvision.datasets import CocoCaptions

class CocoCollate:
    """Custom collate function for COCO captions dataset

    :param dict stoi: Mapping defining integer values for each word in the vocabulary
    """

    def __init__(self, stoi, padding_idx=-1):
        self.stoi = stoi
        self.unk = len(self.stoi)
        self.padding_idx = padding_idx

    def __call__(self, batch):
        """Randomly sample caption and numericalize using mapping

        :param tuple(torch.tensor, [[str]]) batch: 3-channel image data and nested
            lists of potential captions (5 per sample)
        :return tuple(torch.tensor): Batched images and numericalized captions
        """
        images, captions = zip(*batch)
        spell = SpellChecker(distance=1)
        selected = [[word if word in self.stoi else spell.correction(word)
                     for word in re.findall(r"[&lt;&gt;\w']+|[.,!?;]", pick)]
                    for pick in [f'&lt;s&gt; {c[random.randrange(5)].lower()} &lt;/s&gt;' for c in captions]]
        numericalized = [torch.tensor([self.stoi.get(word, self.unk) for word in s]) for s in selected]
        packed = nn.utils.rnn.pad_sequence(numericalized, batch_first=True, padding_value=self.padding_idx)
        return torch.stack(images), packed

transform = transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])
trainset = datasets.CocoCaptions('/path/to/images', '/path/to/captions', transform)
vocabulary = [ ... ]
stoi = {word: idx for idx, word in enumerate(vocabulary)}
loader = DataLoader(trainset, batch_size=2, collate_fn=CocoCollate(stoi))
</code></pre>

hm2092: <p>Hi <a class="mention" href="/u/addisonklinke">@addisonklinke</a>. In my case i made a mistake with the index corresponding to batch size. Whenever i used a batch size &gt; 1 (rarely because of gpu restrictions), i could not copy the whole tensor into the new one, which resulted in the error. But my traceback pointed to conv3d layer(as shown in my post) instead of the copy operation 2 lines before, which made it confusing.</p>
<p>For your second question: I havn’t used pytorch &gt; 0.4 or coco dataset, so i am not sure about it. One thing i know is that the default collate function (pytorch 0.4) use torch.stack function call, which expects the input tensors to have same shape (i had input tensors of different shape). So if coco has images of same shape, then there is no need to use custom collate function. I am neither familiar with captions in your case nor with the latest pytorch releases, sorry.</p>

addisonklinke: <p><a class="mention" href="/u/hm2092">@hm2092</a> If it was just the COCO images, then you are correct that the default collate function would work fine. The need for a custom one is to handle the captions. The <code>__getitem__</code> method of the built-in <code>CocoCaptions</code> dataset class returns the images and a list of strings, so my collate function converts the strings to word indices and pads them to equal length so that <code>torch.stack</code> will work</p>
<p>This is with pytorch 1.4.0 installed through conda, so I may try downgrading to 1.2 or 1.3</p>
<p><strong>Edit:</strong> Found out my issue was passing an out-of-bounds index (-1 in my case) to <code>nn.Embedding</code>. Previous discussion from other users around embedding-related errors can be found on this <a href="https://discuss.pytorch.org/t/solved-assertion-srcindex-srcselectdimsize-failed-on-gpu-for-torch-cat/1804/10">thread</a></p>