C++/cuda custom function: RuntimeError: CUDA error: invalid device function

username: sbelharbi
cooked: <p>hi,<br>
i am using a c++/cuda custom extension.<br>
when running the extension, i get this error:</p>
<pre><code class="lang-auto">RuntimeError: CUDA error: invalid device function
</code></pre>
<p>at the very first call of a function in the extension.</p>
<p>could the nvcc version and cuda versions be the <a href="https://www.gitmemory.com/issue/mapillary/inplace_abn/174/776974541" rel="noopener nofollow ugc">cause</a> since pytorch is shipped with its cuda?</p>
<p>the packages are maintained in a conda env.<br>
the custom function was installed with:</p>
<pre><code class="lang-auto">python setup.y build
python setup.y install
</code></pre>
<p>within the virtual env.<br>
this is the <code>setup.py</code> file:</p>
<pre><code class="lang-python">from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension

setup(
    name='extensions',
    ext_modules=[
        CUDAExtension('HT_opp', [
            'cuda_opps/HT.cpp',
            'cuda_opps/HT_kernel.cu',
        ]),
    ],
    cmdclass={
        'build_ext': BuildExtension
    })
</code></pre>
<p>i am using a pytorch module that is using the extension.<br>
the error is raised in this module when calling a function in the extension.</p>
<p>python 3.7.9<br>
pytorch 1.9.0 installed with <code>conda install pytorch==1.9.0 torchvision==0.10.0 cudatoolkit=11.1 -c pytorch -c nvidia</code></p>
<p>$ nvcc --version<br>
nvcc: NVIDIA (R) Cuda compiler driver<br>
Copyright (c) 2005-2018 NVIDIA Corporation<br>
Built on Sat_Aug_25_21:08:01_CDT_2018<br>
Cuda compilation tools, release 10.0, V10.0.130</p>
<p>CUDA Version of <code>nvidia-smi</code>: 11.1</p>
<p>still reading <a href="https://pytorch.org/tutorials/advanced/cpp_extension.html" rel="noopener nofollow ugc">this</a>…</p>
<p>thanks</p>

username: ptrblck
cooked: <p><code>CUDA error: invalid device function</code> could point to an architecture mismatch, i.e. I guess you are using a CUDA function potentially specified for another compute capability or are building for the from architecture. Since the issue is raised in your custom CUDA code, it’s a bit hard to be more specific.</p>

username: sbelharbi
cooked: <p>thank you!<br>
is there a way to tell for what compute capability a code was designed?<br>
<a href="https://github.com/SamuelJoutard/Permutohedral_attention_module/tree/master/PAM_cuda" rel="noopener nofollow ugc">here</a> is the c++/cuda code.<br>
it was developed almost 2 years ago.<br>
the file <code>pl.py</code> is the pytorch module that uses the extension <code>HT_opp</code>. the code of the extension is in <code>cuda_opps</code>.<br>
the authors did not specify any requirements or specificity about the gpu.<br>
i left them an issue about this since ~24h. no news yet.</p>
<p>thanks again</p>

username: ptrblck
cooked: <p>The custom CUDA extension build steps should either use <code>TORCH_CUDA_ARCH_LIST</code> or should check your local GPUs to select the compute capability. You could try to set <code>TORCH_CUDA_ARCH_LIST</code> manually and if this doesn’t work try to narrow down the offending operation, which creates the issue.</p>

username: sbelharbi
cooked: <p>thanks.<br>
my gpu is a teslap100 which is supposed to have a <a href="https://developer.nvidia.com/cuda-gpus" rel="noopener nofollow ugc">compute</a> capa. of 6.0.</p>
<p>i tried with <code>TORCH_CUDA_ARCH_LIST="6.0+PTX" python setup.py build</code>, but nothing changed. i got the same error.</p>
<p>the doc says that by default, <code>torch.utils.cpp_extension.CUDAExtension</code> will build for all the visible archs.<br>
so, it is supposed to build for the right cc. there are 2 gpus with same arch.</p>
<p>found similar issue with a <a href="https://github.com/HapeMask/crfrnn_layer/issues/7#issue-988382478" rel="noopener nofollow ugc">code</a> from another repo.</p>
<p>the error message is so vague. and it does not point to any file.<br>
there is no makefile to change the cc as suggested <a href="https://github.com/BVLC/caffe/issues/138" rel="noopener nofollow ugc">here</a>.</p>
<p>i tried this on 2 servers with 2 different hardware but similar virtual env.</p>
<p>i dont know how to get what is offending cuda.<br>
either the code of cuda extension does not go well with the current version cuda/pytorch.<br>
or something is wrong with the installation (conda)…</p>
<p>does current cuda version still support old cuda code?<br>
not an expert in cuda, but when writing cuda extensions, does one needs to know before hand the gpu arch? if it is the case, it will make the code almost useless…</p>
<p>when the built of the cuda extension is successful, is there any reason that there will be issues at runtime, provided that the inputs are correct? since the extension is supposed to be built for all arch. i assume at the runtime it will choose the right arch for the current gpu.</p>
<p>i ll try to check their cuda code. when edited, it has to be rebuilt to check the impact.<br>
i still lean toward that this may be caused by nvcc, pytorch, cuda, cc, conda incompatible versions that do not go well with the cuda extension code… but again, i am not an expert.</p>
<p>i thought extensions are easy to use. once the cuda/c++ part were written, which is the hard part, the rest is plug and play as presented in the <a href="https://pytorch.org/tutorials/advanced/cpp_extension.html" rel="noopener nofollow ugc">tutorial</a>. you build and call. what could go wrong? the built is successful, the installation is successful.</p>
<p>i learned somewhere that when importing the extension, when needs to import torch first to prepare some stuff (links to libs …)</p>
<p>so, it seems cuda extension code and pytorch cuda code maybe need to be built with the same versions or compatible versions at least. what it it is not the case? i installed the conda pre-built version, and i compiled this cuda extension on my machine. is there a chance that this difference in compilation could cause any issue?</p>
<p>i cant even tell what is wrong from that message error.<br>
is there a way to make cuda tell a more helpful error? there should be a way to debug extensions, right?<br>
does pytorch has some debugging tools for extensions  to tell what’s wrong?</p>
<p>i really appreciate your help.<br>
been stuck for 6 days at this stage. build and test one of these repos. it is a minor step. it could be done in 10 mins. 6 days later, and here i am unable to run a simple test provided by the authors.<br>
authors didnt reply yet. i also sent an email. some seem in vacation.<br>
will let you know.</p>
<p>thank you again</p>

username: ptrblck
cooked: <aside class="quote no-group" data-username="sbelharbi" data-post="5" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>i tried with <code>TORCH_CUDA_ARCH_LIST="6.0+PTX" python setup.py build</code>, but nothing changed. i got the same error.</p>
</blockquote>
</aside>
<p>This could mean that the built binary itself should be correct.</p>
<aside class="quote no-group" data-username="sbelharbi" data-post="5" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>the doc says that by default, <code>torch.utils.cpp_extension.CUDAExtension</code> will build for all the visible archs.<br>
so, it is supposed to build for the right cc. there are 2 gpus with same arch.</p>
</blockquote>
</aside>
<p>Yes, assuming you are using the latest PyTorch release.</p>
<aside class="quote no-group" data-username="sbelharbi" data-post="5" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>i dont know how to get what is offending cuda.<br>
either the code of cuda extension does not go well with the current version cuda/pytorch.<br>
or something is wrong with the installation (conda)…</p>
</blockquote>
</aside>
<p>Your setup seems to be the issue, since you are mixing the CUDA runtime used in the PyTorch binaries (11.1) with the local CUDA toolkit used to build the extension (10.0), so you would need to stick to the same version. I’ve rebuild the extension on a server with a P100 using matching CUDA versions and this code snippet works fine:</p>
<pre data-code-wrap="python"><code class="lang-python">from PAM_cuda.pl import PermutohedralLattice

if __name__ == '__main__':
    import numpy as np
    pl = PermutohedralLattice.apply

    im = torch.randn(24, 24, 3)
    indices = np.reshape(np.indices(im.shape[:2]), (2, -1))[None, :]
    im = im.permute(2, 0, 1)
    rgb = im.reshape(3, -1).unsqueeze(0)
    out = pl(torch.from_numpy(indices / 5.0).cuda().float(),
             (rgb / 0.125).cuda().float())

    output = out.squeeze().cpu().numpy()
    output = np.transpose(output, (1, 0))
    output = np.reshape(output, (im.shape[1], im.shape[2], 3))
    print(output)
</code></pre>

username: sbelharbi
cooked: <p>thank you very much.<br>
indeed, the conflict between cuda local and the one used to built pytorch was the causse of the issue.<br>
after fixing the nvcc path to the rigth cuda, it worked.</p>
<p>i relied on nvidia-smi to get the right cuda version, but i shouldnt have.<br>
<code>nvcc -V</code> is the right tool.</p>
<p>one question: can we compile the extension without gpu available, but it will be available later?<br>
in some clusters, we have access to the frontal where there is no gpus. it is upon request that we are allocated gpus.<br>
i read in the <a href="https://pytorch.org/tutorials/advanced/cpp_extension.html" rel="noopener nofollow ugc">doc</a>, that there are 2 ways to build extensions: ahead and just in time.<br>
so, in my case, i should probably use the second option.<br>
but i was wondering if the first option is viable? so i do the install only once.</p>
<p>i think my answer is in the doc that we cant do the first option in this case, right?</p>
<pre><code class="lang-auto">By default the extension will be compiled to run on all archs of the cards visible during the building 
process of the extension, plus PTX. 
If down the road a new card is installed the extension may need to be recompiled. 
</code></pre>
<p>they said <code>may</code> need to be recompiled and not have… so, not sure.</p>
<p>in case i use jit method and there are multiple gpus. 2  cases are presented:</p>
<ol>
<li>my code will use only one (more likely to not know which one the moment when loading the extension)</li>
<li>my code will use miltui-gpus with ddp (what if gpus have different arch??).</li>
</ol>
<p>i assume that jit will handle both cases automatically without any additional config. right?</p>
<p>about the runtime when using jit. from the doc:</p>
<pre><code class="lang-auto">lltm_cpp = load(name="lltm_cpp", sources=["lltm.cpp"])

The first time you run through this line, it will take some time, as the extension is compiling 
in the background. Since we use the Ninja build system to build your sources, re-compilation is
 incremental and thus re-loading the extension when you run your Python module a second 
time is fast and has low overhead if you didn’t change the extension’s source files.
</code></pre>
<p>i assume the expensive time they are talking about is the <code>loading</code> when the compilation happens.<br>
once loaded, the runtime of calling is the same as the ahead-method.<br>
i mention this because in my case, every time i run my code, it is allocated a new different gpu. so, the compilation directory will be dependent on the job and it will temporary (i.e. will be deleted after the job is done.).  when using ddp, i can set that only the main process will load/compile the extension. once done, the other processes will have access to it.<br>
thanks</p>
<p>this experience brings me to this natural question related to compiling extensions and this versions issue:</p>
<p>i read several times that when installing pytorch using <code>conda install pytorch==1.9.0 cudatoolkit=11.1 -c pytorch -c nvidia</code>, that cuda toolkit will be shipped with the installation.</p>
<p>i read other answers about this including <a href="https://discuss.pytorch.org/t/is-it-required-to-set-up-cuda-on-pc-before-installing-cuda-enabled-pytorch/60181/15">yours</a> and this <a href="https://discuss.pytorch.org/t/install-pytorch-gpu-with-pre-installed-cuda-and-cudnn/70808/2">one</a>.</p>
<p>because the nvcc is part of the cuda toolkit and not the driver, i assume that nvcc is shipped with the installation as well. is that right?</p>
<p>by the way, i did a search in the virtual env of conda for cuda toolkit, nvcc, and i couldnt find any. probably they are hidden in a lib or something. do you know where they are installed?</p>
<p>i think you know now where i am going with this.<br>
if we have access to the cuda toolkit that was used to build the installed binary of pytorch,  and since this last one wont using anyway the local install of cuda runtime, could we use the shipped cuda toolkit to compile new extensions allowing us to be independent from the local cuda runtime installation (that could be not up to date,  messy, …)?<br>
this could be a huge benefit because we are sure that the extension is complied with the same exact cuda version that was used to build pytorch, right?</p>
<p>you said yourself in the threads mentioned above, that when compiling extensions with pytorch that was installed as above (i.e. with the shipped cuda toolkit), one needs to install locally  the same version as the one used to built pytorch. if we have access to the shipped  nvcc and cuda stuff could we skip this install step? or there are other things necessary for the compilation that were not shipped? <a href="https://discuss.pytorch.org/t/is-it-required-to-set-up-cuda-on-pc-before-installing-cuda-enabled-pytorch/60181/2">one</a> of the comments mentioned that cuda lib is huge to be shipped with pytorch. that comment was in 2019, because in the same thread, and in 2020, you said that cuda toolkit is shipped. i am not sure if there is a difference between cuda toolkit and cuda library.</p>
<p>again, thank you very much for solving this issue. it was a huge help.<br>
i really appreciate it!</p>
<p>i apologize for the long comment</p>

username: ptrblck
cooked: <aside class="quote no-group" data-username="sbelharbi" data-post="7" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>one question: can we compile the extension without gpu available, but it will be available later?<br>
in some clusters, we have access to the frontal where there is no gpus. it is upon request that we are allocated gpus.</p>
</blockquote>
</aside>
<p>Yes, you can cross-compile for different architectures and create a pip wheel, but given the issues you were seeing in the past the JIT compilation might be the easier path for now.</p>
<aside class="quote no-group" data-username="sbelharbi" data-post="7" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>i assume the expensive time they are talking about is the <code>loading</code> when the compilation happens.<br>
once loaded, the runtime of calling is the same as the ahead-method.</p>
</blockquote>
</aside>
<p>The “expensive time” is used during the initial compilation and the next call will use the already built and cached lib, so will be much faster. E.g. using <a href="https://github.com/pytorch/extension-cpp">this</a> example I get an initial startup time of:</p>
<pre data-code-wrap="python"><code class="lang-python">Loading extension module lltm...

real	2m13.153s
user	2m14.363s
sys	0m16.594s
</code></pre>
<p>and further calls need:</p>
<pre data-code-wrap="python"><code class="lang-python">Loading extension module lltm...

real	0m1.984s
user	0m2.198s
sys	0m6.165s
</code></pre>
<aside class="quote no-group" data-username="sbelharbi" data-post="7" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>i read several times that when installing pytorch using <code>conda install pytorch==1.9.0 cudatoolkit=11.1 -c pytorch -c nvidia</code>, that cuda toolkit will be shipped with the installation.</p>
</blockquote>
</aside>
<p>No, that’s not correct, as only the runtime is shipped, not the entire CUDA toolkit.</p>
<aside class="quote no-group" data-username="sbelharbi" data-post="7" data-topic="131085">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/s/f475e1/48.png" class="avatar"> sbelharbi:</div>
<blockquote>
<p>because the nvcc is part of the cuda toolkit and not the driver, i assume that nvcc is shipped with the installation as well. is that right?</p>
</blockquote>
</aside>
<p>No, it’s not part of the conda <code>cudatoolkit</code> binaries.</p>

username: sbelharbi
cooked: <p>ok, that clarifies things.<br>
thank you very much for your help!</p>