CUDA error: CUBLAS_STATUS_INVALID_VALUE

username: machina
cooked: <p>RESOLVED: resolved it the issue, disc() (fc1) took size [32, 784] and I had the input tensor (adv_ex) as [32,28,28]</p>
<p>Receiving a runtime error and I’m not sure why this line is causing it.<br>
Here is the code block:</p>
<pre><code class="lang-auto">for epoch in range(num_epochs):
    for batch_idx, (real, labels) in enumerate(loader):
        #get a fixed input batch to display gen output
        if batch_idx == 0:
            if epoch == 0:
                fixed_input = real.view(-1,784).to(device)
        
        adv_ex = real.clone().reshape(-1,784).to(device) # [32, 784] advex copy of first batch flattened
        real = real.view(-1, 784).to(device) # [32, 784] # real batch flattened
        labels = labels.to(device) # size() [32] 32 labels in batch
        
        
        #purturb each image in adv_ex
        tmp_adv_ex = []
        for idx, item in enumerate(adv_ex):
            purturbation = gen(adv_ex[idx])
            tmp_adv_ex.append(adv_ex[idx] + purturbation)
        adv_ex = torch.cat(tmp_adv_ex, dim=0)
        adv_ex = real.clone().reshape(-1,784).to(device)
        
         
        ### Train Generator: min log(1 - D(G(z))) &lt;-&gt; max log(D(G(z))
        output = disc(adv_ex).view(-1)
        lossG = torch.mean(torch.log(1. - output)) #get loss for gen's desired desc pred

        adv_ex = adv_ex.reshape(-1,1,28,28)
        f_pred = target(adv_ex)
        f_loss = CE_loss(f_pred, labels) #add loss for gens desired f pred
        loss_G_Final = f_loss+lossG # can change the weight of this loss term later

        opt_gen.zero_grad()
        loss_G_Final.backward()
        opt_gen.step()
        
        ### Train Discriminator: max log(D(x)) + log(1 - D(G(z)))
        
        disc_real = disc(real).view(-1)
        disc_fake = disc(adv_ex).view(-1)
        lossD = -torch.mean(torch.log(disc(real)) + torch.log(1. - disc(adv_ex)))
        # can decide later how much that loss term weighs
        
        opt_disc.zero_grad()
        lossD.backward(retain_graph=True)
        opt_disc.step()
</code></pre>
<p>This is the error code:</p>
<pre><code class="lang-auto">---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
/tmp/ipykernel_25258/819410292.py in &lt;module&gt;
     47         ### Train Discriminator: max log(D(x)) + log(1 - D(G(z)))
     48         disc_real = disc(real).view(-1)
---&gt; 49         disc_fake = disc(adv_ex).view(-1)
     50         lossD = -torch.mean(torch.log(disc(real)) + torch.log(1. - disc(adv_ex)))
     51         # can decide later how much that loss term weighs

~/.conda/envs/mypytorch19/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-&gt; 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

~/AdvGan9-4/models.py in forward(self, x)
     28 
     29     def forward(self, x):
---&gt; 30         x = self.fc1(x)
     31         x = nn.ReLU()(x)
     32         x = self.fc2(x)

~/.conda/envs/mypytorch19/lib/python3.9/site-packages/torch/nn/modules/module.py in _call_impl(self, *input, **kwargs)
   1049         if not (self._backward_hooks or self._forward_hooks or self._forward_pre_hooks or _global_backward_hooks
   1050                 or _global_forward_hooks or _global_forward_pre_hooks):
-&gt; 1051             return forward_call(*input, **kwargs)
   1052         # Do not call functions when jit is used
   1053         full_backward_hooks, non_full_backward_hooks = [], []

~/.conda/envs/mypytorch19/lib/python3.9/site-packages/torch/nn/modules/linear.py in forward(self, input)
     94 
     95     def forward(self, input: Tensor) -&gt; Tensor:
---&gt; 96         return F.linear(input, self.weight, self.bias)
     97 
     98     def extra_repr(self) -&gt; str:

~/.conda/envs/mypytorch19/lib/python3.9/site-packages/torch/nn/functional.py in linear(input, weight, bias)
   1845     if has_torch_function_variadic(input, weight):
   1846         return handle_torch_function(linear, (input, weight), input, weight, bias=bias)
-&gt; 1847     return torch._C._nn.linear(input, weight, bias)
   1848 
   1849 

RuntimeError: CUDA error: CUBLAS_STATUS_INVALID_VALUE when calling `cublasSgemm( handle, opa, opb, m, n, k, &amp;alpha, a, lda, b, ldb, &amp;beta, c, ldc)`

 ** On entry to SGEMM  parameter number 10 had an illegal value

</code></pre>
<p>How should I interpret this and how should I modify line 49 to resolve it?</p>

username: ptrblck
cooked: <p>Could you post the setup of <code>self.fc1</code> as well as the shape of <code>x</code>?<br>
Also, which device are you using and in case you are using an older PyTorch release, could you update to the latest one and rerun the code, please?</p>

username: machina
cooked: <p>I resolved it the issue,  disc() (fc1) took size [32, 784] and I had the input tensor (adv_ex) as [32,28,28]</p>
<p>This is the current issue that I’m struggling with <a href="https://discuss.pytorch.org/t/mmbackward-returned-an-invalid-gradient-at-index-0/132956" class="inline-onebox">MmBackward returned an invalid gradient at index 0?</a></p>

username: ptrblck
cooked: <p>Which PyTorch version are you using?<br>
A wrong input shape should yield an easy to understand shape mismatch error. The shape check was recently broken, but was fixed in 1.9.1. If you are seeing this error in this version, it would be great to see your code, as this error message is more then unhelpful.</p>

username: machina
cooked: <p>my pytorch version is 1.9.0 and the code for disc() is</p>
<pre><code class="lang-auto">class Discriminator(nn.Module):
    def __init__(self, in_features):
        super().__init__()
        self.fc1 = nn.Linear(in_features, 128)
        self.fc2 = nn.Linear(128, 1)
        
    def forward(self, x):
        x = self.fc1(x)
        x = nn.ReLU()(x)
        x = self.fc2(x)
        x = nn.Sigmoid()(x)
        return x
</code></pre>
<p>is updating torch version just “conda install pytorch”?</p>

username: ptrblck
cooked: <p>Yes, either via conda or pip, depending how you’ve installed it previously.<br>
I know that users here had good experience with updating the binaries, but I’m usually just uninstalling the old ones and reinstall the new one.<br>
In case you are concerned about an update, create a new virtual conda environment and install the latest release there.</p>

username: machina
cooked: <p><div class="lightbox-wrapper"><a class="lightbox" href="https://discuss.pytorch.org/uploads/default/original/3X/a/8/a8c8f8e16dab805431a6038e63f2ba712e9c0a96.png" data-download-href="https://discuss.pytorch.org/uploads/default/a8c8f8e16dab805431a6038e63f2ba712e9c0a96" title="image"><img src="https://discuss.pytorch.org/uploads/default/optimized/3X/a/8/a8c8f8e16dab805431a6038e63f2ba712e9c0a96_2_690x320.png" alt="image" data-base62-sha1="o58NlH1UFPzmSwqjfmORIWFFhMG" width="690" height="320" srcset="https://discuss.pytorch.org/uploads/default/optimized/3X/a/8/a8c8f8e16dab805431a6038e63f2ba712e9c0a96_2_690x320.png, https://discuss.pytorch.org/uploads/default/optimized/3X/a/8/a8c8f8e16dab805431a6038e63f2ba712e9c0a96_2_1035x480.png 1.5x, https://discuss.pytorch.org/uploads/default/original/3X/a/8/a8c8f8e16dab805431a6038e63f2ba712e9c0a96.png 2x" data-dominant-color="0D0D0D"><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">1288×598 182 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><br>
It seems like it didn’t install the later version<br>
should i do conda install pytorch=1.9.1</p>

username: ptrblck
cooked: <p>Yes, use the instructions from the <a href="https://pytorch.org/get-started/locally/">website</a>.</p>