나는 distutils를 사용하여 파이썬에 동적 라이브러리를 만들고 싶습니다. CUDA 코드가 있습니다. 하지만 distutils는 "nvcc"컴파일러가 설치되어 있어도 ".cu"파일을 인식하지 못합니다. 그것을 완료하는 방법을 모르겠습니다.파이썬 distutils가 CUDA 코드를 컴파일 할 수 있습니까?
6
A
답변
11
Distutils는 다중 컴파일러를 동시에 사용할 수 없기 때문에 기본적으로 CUDA를 컴파일 할 수 없습니다. 기본적으로 플랫폼에 기반한 컴파일러로 설정하고 소스 코드의 유형에는 설정하지 않습니다.
distutils에 원숭이 패치가 들어있는 github 예제 프로젝트에서이를 지원합니다. 예제 프로젝트는 일부 GPU 메모리와 CUDA 커널을 관리하고 swig로 랩핑 한 C++ 클래스이며 모두 python setup.py install
으로 컴파일됩니다. 배열 작업에 중점을두고 있으므로 numpy도 사용하고 있습니다. 이 예제 프로젝트에서 커널이 수행하는 모든 작업은 배열의 각 요소를 하나씩 증가시킵니다.
코드는 여기 https://github.com/rmcgibbo/npcuda-example입니다. 다음은 setup.py 스크립트입니다. 전체 코드의 핵심은 customize_compiler_for_nvcc()
입니다.
import os
from os.path import join as pjoin
from setuptools import setup
from distutils.extension import Extension
from distutils.command.build_ext import build_ext
import subprocess
import numpy
def find_in_path(name, path):
"Find a file in a search path"
#adapted fom http://code.activestate.com/recipes/52224-find-a-file-given-a-search-path/
for dir in path.split(os.pathsep):
binpath = pjoin(dir, name)
if os.path.exists(binpath):
return os.path.abspath(binpath)
return None
def locate_cuda():
"""Locate the CUDA environment on the system
Returns a dict with keys 'home', 'nvcc', 'include', and 'lib64'
and values giving the absolute path to each directory.
Starts by looking for the CUDAHOME env variable. If not found, everything
is based on finding 'nvcc' in the PATH.
"""
# first check if the CUDAHOME env variable is in use
if 'CUDAHOME' in os.environ:
home = os.environ['CUDAHOME']
nvcc = pjoin(home, 'bin', 'nvcc')
else:
# otherwise, search the PATH for NVCC
nvcc = find_in_path('nvcc', os.environ['PATH'])
if nvcc is None:
raise EnvironmentError('The nvcc binary could not be '
'located in your $PATH. Either add it to your path, or set $CUDAHOME')
home = os.path.dirname(os.path.dirname(nvcc))
cudaconfig = {'home':home, 'nvcc':nvcc,
'include': pjoin(home, 'include'),
'lib64': pjoin(home, 'lib64')}
for k, v in cudaconfig.iteritems():
if not os.path.exists(v):
raise EnvironmentError('The CUDA %s path could not be located in %s' % (k, v))
return cudaconfig
CUDA = locate_cuda()
# Obtain the numpy include directory. This logic works across numpy versions.
try:
numpy_include = numpy.get_include()
except AttributeError:
numpy_include = numpy.get_numpy_include()
ext = Extension('_gpuadder',
sources=['src/swig_wrap.cpp', 'src/manager.cu'],
library_dirs=[CUDA['lib64']],
libraries=['cudart'],
runtime_library_dirs=[CUDA['lib64']],
# this syntax is specific to this build system
# we're only going to use certain compiler args with nvcc and not with gcc
# the implementation of this trick is in customize_compiler() below
extra_compile_args={'gcc': [],
'nvcc': ['-arch=sm_20', '--ptxas-options=-v', '-c', '--compiler-options', "'-fPIC'"]},
include_dirs = [numpy_include, CUDA['include'], 'src'])
# check for swig
if find_in_path('swig', os.environ['PATH']):
subprocess.check_call('swig -python -c++ -o src/swig_wrap.cpp src/swig.i', shell=True)
else:
raise EnvironmentError('the swig executable was not found in your PATH')
def customize_compiler_for_nvcc(self):
"""inject deep into distutils to customize how the dispatch
to gcc/nvcc works.
If you subclass UnixCCompiler, it's not trivial to get your subclass
injected in, and still have the right customizations (i.e.
distutils.sysconfig.customize_compiler) run on it. So instead of going
the OO route, I have this. Note, it's kindof like a wierd functional
subclassing going on."""
# tell the compiler it can processes .cu
self.src_extensions.append('.cu')
# save references to the default compiler_so and _comple methods
default_compiler_so = self.compiler_so
super = self._compile
# now redefine the _compile method. This gets executed for each
# object but distutils doesn't have the ability to change compilers
# based on source extension: we add it.
def _compile(obj, src, ext, cc_args, extra_postargs, pp_opts):
if os.path.splitext(src)[1] == '.cu':
# use the cuda for .cu files
self.set_executable('compiler_so', CUDA['nvcc'])
# use only a subset of the extra_postargs, which are 1-1 translated
# from the extra_compile_args in the Extension class
postargs = extra_postargs['nvcc']
else:
postargs = extra_postargs['gcc']
super(obj, src, ext, cc_args, postargs, pp_opts)
# reset the default compiler_so, which we might have changed for cuda
self.compiler_so = default_compiler_so
# inject our redefined _compile method into the class
self._compile = _compile
# run the customize_compiler
class custom_build_ext(build_ext):
def build_extensions(self):
customize_compiler_for_nvcc(self.compiler)
build_ext.build_extensions(self)
setup(name='gpuadder',
# random metadata. there's more you can supploy
author='Robert McGibbon',
version='0.1',
# this is necessary so that the swigged python file gets picked up
py_modules=['gpuadder'],
package_dir={'': 'src'},
ext_modules = [ext],
# inject our custom trigger
cmdclass={'build_ext': custom_build_ext},
# since the package has c code, the egg cannot be zipped
zip_safe=False)
+1
일종의 오래된 질문이지만 창문에서이 작업을 수행하는 방법을 알고 있습니까? 문제는 ** _ compile ** 메소드가 ** msvccompiler **에 의해 사용되지 않는다는 것입니다. – rAyyy
관련 문제
- 1. 파이썬의 distutils가 .S (어셈블리)를 컴파일 할 수 있습니까?
- 2. 어떻게하면 CUDA 코드를 컴파일하여 C++ 프로젝트에 링크 할 수 있습니까?
- 3. gedit에서 파이썬 코드를 컴파일
- 4. apdfviewer에서 원시 코드를 컴파일 할 수 있습니까?
- 5. Amazon EC2에서 코드를 컴파일 할 수 있습니까?
- 6. antlr은 파이썬 코드를 생성 할 수 있습니까?
- 7. 어떻게 최적화하지 않고도 cuda 커널을 컴파일 할 수 있습니까?
- 8. pyc 바이트 코드를 넘어서 기본적으로 파이썬을 컴파일 할 수 있습니까?
- 9. CUDA 컴파일 오류
- 10. CUDA SDK 컴파일 오류
- 11. CUDA 컴파일 오류
- 12. clang으로 CUDA 컴파일
- 13. 전체 파이썬 패키지를 사전 컴파일 할 수 있습니까?
- 14. 쿠다 코드를 컴파일 할 수 없습니다
- 15. 서블릿 코드를 컴파일 할 수 없습니다.
- 16. 컴파일 된 파이썬 파일을 가져올 수 있습니까?
- 17. 정수로 CUDA 텍스처를 색인 할 수 있습니까?
- 18. Macports의 GCC를 사용하여 범용 코드를 컴파일 할 수 있습니까?
- 19. VS 플러그인이 코드를 컴파일 프로세스에 삽입 할 수 있습니까?
- 20. Windows에서 Linux 용으로 작성된 C 코드를 컴파일 할 수 있습니까?
- 21. 누구나 gVIM 소스 코드를 변경하여 컴파일 할 수 있습니까?
- 22. 여러 플랫폼에서 실행되도록 Objective-C 코드를 컴파일 할 수 있습니까?
- 23. Build AST를하는 대신 Xcode에서 내 코드를 컴파일 할 수 있습니까?
- 24. Mac에서 C++ 코드를 .exe로 컴파일 할 수 있습니까?
- 25. DLR은 클라이언트 측 코드를 컴파일 할 수 있습니까?
- 26. 컴파일 된 SWF에 코드를 추가 할 수 있습니까?
- 27. iPad 용 Fortran 코드를 컴파일 할 수 있습니까?
- 28. C 코드를 Javascript 코드로 컴파일 할 수 있습니까?
- 29. MSVC++에서 어셈블리 코드를 컴파일 할 수 있습니까?
- 30. 어떻게하면 memcached-1.4.7의 소스 코드를 컴파일 할 수 있습니까?
시도한 것을 볼 수 있도록 코드를 게시 할 수 있습니까? 또한, CUDA 커널이 핵심 부분이라면, PyCUDA를 사용하여 파이썬에서 사용할 수있게 할 수 있습니다. –
'인식하지 못함'이란 무엇을 의미합니까? 달걀에 .cu 파일을 포함시키지 않습니까? package_data 추가 = { '': [ '* .CU']} 다음 설정 (...)합니다. –