144 from __future__
import print_function
145 from setuptools
import setup, Extension, distutils, Command, find_packages
146 from distutils
import core, dir_util
147 from distutils.core
import Distribution
148 from distutils.errors
import DistutilsArgError
149 import setuptools.command.build_ext
150 import setuptools.command.install
151 import distutils.command.clean
152 import distutils.sysconfig
166 DEBUG, REL_WITH_DEB_INFO, USE_MKLDNN)
177 VERBOSE_SCRIPT =
True 178 RUN_BUILD_DEPS =
True 181 EMIT_BUILD_WARNING =
False 184 for i, arg
in enumerate(sys.argv):
188 if arg ==
'rebuild' or arg ==
'build':
190 EMIT_BUILD_WARNING =
True 192 filtered_args += sys.argv[i:]
194 if arg ==
'-q' or arg ==
'--quiet':
195 VERBOSE_SCRIPT =
False 197 RUN_BUILD_DEPS =
False 198 filtered_args.append(arg)
199 sys.argv = filtered_args
209 cwd = os.path.dirname(os.path.abspath(__file__))
210 lib_path = os.path.join(cwd,
"torch",
"lib")
211 third_party_path = os.path.join(cwd,
"third_party")
212 caffe2_build_dir = os.path.join(cwd,
"build")
214 rel_site_packages = distutils.sysconfig.get_python_lib(prefix=
'')
216 full_site_packages = distutils.sysconfig.get_python_lib()
219 cmake_python_library =
"{}/libs/python{}.lib".format(
220 distutils.sysconfig.get_config_var(
"prefix"),
221 distutils.sysconfig.get_config_var(
"VERSION"))
223 cmake_python_library =
"{}/{}".format(
224 distutils.sysconfig.get_config_var(
"LIBDIR"),
225 distutils.sysconfig.get_config_var(
"INSTSONAME"))
226 cmake_python_include_dir = distutils.sysconfig.get_python_inc()
232 package_name = os.getenv(
'TORCH_PACKAGE_NAME',
'torch')
234 if os.getenv(
'PYTORCH_BUILD_VERSION'):
235 assert os.getenv(
'PYTORCH_BUILD_NUMBER')
is not None 236 build_number = int(os.getenv(
'PYTORCH_BUILD_NUMBER'))
237 version = os.getenv(
'PYTORCH_BUILD_VERSION')
239 version +=
'.post' + str(build_number)
242 sha = subprocess.check_output([
'git',
'rev-parse',
'HEAD'], cwd=cwd).decode(
'ascii').strip()
243 version +=
'+' + sha[:7]
246 report(
"Building wheel {}-{}".format(package_name, version))
251 report(
'-- Building version ' + version)
252 version_path = os.path.join(cwd,
'torch',
'version.py')
253 with open(version_path,
'w')
as f:
254 f.write(
"__version__ = '{}'\n".format(version))
258 f.write(
"debug = {}\n".format(repr(DEBUG)))
259 f.write(
"cuda = {}\n".format(repr(CUDA_VERSION)))
262 if not os.path.exists(f):
263 report(
"Could not find {}".format(f))
264 report(
"Did you run 'git submodule update --init --recursive'?")
267 check_file(os.path.join(third_party_path,
"gloo",
"CMakeLists.txt"))
268 check_file(os.path.join(third_party_path,
"pybind11",
"CMakeLists.txt"))
269 check_file(os.path.join(third_party_path,
'cpuinfo',
'CMakeLists.txt'))
270 check_file(os.path.join(third_party_path,
'onnx',
'CMakeLists.txt'))
271 check_file(os.path.join(third_party_path,
'foxi',
'CMakeLists.txt'))
272 check_file(os.path.join(third_party_path,
'QNNPACK',
'CMakeLists.txt'))
273 check_file(os.path.join(third_party_path,
'fbgemm',
'CMakeLists.txt'))
275 check_pydep(
'yaml',
'pyyaml')
276 check_pydep(
'typing',
'typing')
278 build_caffe2(version=version,
279 cmake_python_library=cmake_python_library,
281 rerun_cmake=RERUN_CMAKE,
286 sym_files = [
'tools/shared/cwrap_common.py',
'tools/shared/_utils_internal.py']
287 orig_files = [
'aten/src/ATen/common_with_cwrap.py',
'torch/_utils_internal.py']
288 for sym_file, orig_file
in zip(sym_files, orig_files):
290 if os.path.exists(sym_file):
291 if filecmp.cmp(sym_file, orig_file):
296 shutil.copyfile(orig_file, sym_file)
298 dir_util.copy_tree(
'third_party/pybind11/include/pybind11/',
299 'torch/include/pybind11')
306 Missing build dependency: Unable to `import {importname}`. 307 Please install it via `conda install {module}` or `pip install {module}` 311 def check_pydep(importname, module):
313 importlib.import_module(importname)
315 raise RuntimeError(missing_pydep.format(importname=importname, module=module))
318 class build_ext(setuptools.command.build_ext.build_ext):
322 report(
'-- Building with NumPy bindings')
324 report(
'-- NumPy not found')
326 report(
'-- Detected cuDNN at ' + CUDNN_LIBRARY +
', ' + CUDNN_INCLUDE_DIR)
328 report(
'-- Not using cuDNN')
330 report(
'-- Detected MIOpen at ' + MIOPEN_LIBRARY +
', ' + MIOPEN_INCLUDE_DIR)
332 report(
'-- Not using MIOpen')
334 report(
'-- Detected CUDA at ' + CUDA_HOME)
336 report(
'-- Not using CUDA')
338 report(
'-- Using MKLDNN')
340 report(
'-- Not using MKLDNN')
341 if USE_NCCL
and USE_SYSTEM_NCCL:
342 report(
'-- Using system provided NCCL library at ' + NCCL_SYSTEM_LIB +
', ' + NCCL_INCLUDE_DIR)
344 report(
'-- Building NCCL library')
346 report(
'-- Not using NCCL')
348 report(
'-- Building with THD distributed package ')
350 report(
'-- Building with c10d distributed package ')
352 report(
'-- Building without c10d distributed package')
354 report(
'-- Building without distributed package')
357 setuptools.command.build_ext.build_ext.run(self)
361 build_temp = self.build_temp
363 ext_filename = self.get_ext_filename(
'_C')
364 lib_filename =
'.'.join(ext_filename.split(
'.')[:-1]) +
'.lib' 366 export_lib = os.path.join(
367 build_temp,
'torch',
'csrc', lib_filename).replace(
'\\',
'/')
369 build_lib = self.build_lib
371 target_lib = os.path.join(
372 build_lib,
'torch',
'lib',
'_C.lib').replace(
'\\',
'/')
374 self.copy_file(export_lib, target_lib)
376 def build_extensions(self):
385 caffe2_pybind_exts = [
386 'caffe2.python.caffe2_pybind11_state',
387 'caffe2.python.caffe2_pybind11_state_gpu',
388 'caffe2.python.caffe2_pybind11_state_hip',
391 while i < len(self.extensions):
392 ext = self.extensions[i]
393 if ext.name
not in caffe2_pybind_exts:
396 fullname = self.get_ext_fullname(ext.name)
397 filename = self.get_ext_filename(fullname)
398 report(
"\nCopying extension {}".format(ext.name))
400 src = os.path.join(
"torch", rel_site_packages, filename)
401 if not os.path.exists(src):
402 report(
"{} does not exist".format(src))
403 del self.extensions[i]
405 dst = os.path.join(os.path.realpath(self.build_lib), filename)
406 report(
"Copying {} from {} to {}".format(ext.name, src, dst))
407 dst_dir = os.path.dirname(dst)
408 if not os.path.exists(dst_dir):
410 self.copy_file(src, dst)
412 distutils.command.build_ext.build_ext.build_extensions(self)
414 def get_outputs(self):
415 outputs = distutils.command.build_ext.build_ext.get_outputs(self)
416 outputs.append(os.path.join(self.build_lib,
"caffe2"))
417 report(
"setup.py::get_outputs returning {}".format(outputs))
420 def create_compile_commands(self):
422 with open(filename)
as f:
424 ninja_files = glob.glob(
'build/*compile_commands.json')
425 cmake_files = glob.glob(
'torch/lib/build/*/compile_commands.json')
426 all_commands = [entry
427 for f
in ninja_files + cmake_files
428 for entry
in load(f)]
434 for command
in all_commands:
435 if command[
'command'].startswith(
"gcc "):
436 command[
'command'] =
"g++ " + command[
'command'][4:]
438 new_contents = json.dumps(all_commands, indent=2)
440 if os.path.exists(
'compile_commands.json'):
441 with open(
'compile_commands.json',
'r') as f: 443 if contents != new_contents:
444 with open(
'compile_commands.json',
'w')
as f:
445 f.write(new_contents)
448 class install(setuptools.command.install.install):
450 setuptools.command.install.install.run(self)
453 class clean(distutils.command.clean.clean):
457 with open(
'.gitignore',
'r') as f: 459 pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?')
460 for wildcard
in filter(
None, ignores.split(
'\n')):
461 match = pat.match(wildcard)
468 for filename
in glob.glob(wildcard):
472 shutil.rmtree(filename, ignore_errors=
True)
475 distutils.command.clean.clean.run(self)
487 extra_link_args = [
'/NODEFAULTLIB:LIBCMT.LIB']
495 extra_compile_args = [
'/MD',
'/Z7',
496 '/EHa',
'/DNOMINMAX',
497 '/wd4267',
'/wd4251',
'/wd4522',
'/wd4522',
'/wd4838',
498 '/wd4305',
'/wd4244',
'/wd4190',
'/wd4101',
'/wd4996',
500 if sys.version_info[0] == 2:
501 if not check_env_flag(
'FORCE_PY27_BUILD'):
502 report(
'The support for PyTorch with Python 2.7 on Windows is very experimental.')
503 report(
'Please set the flag `FORCE_PY27_BUILD` to 1 to continue build.')
507 extra_compile_args.append(
'/bigobj')
510 extra_compile_args = [
514 '-Wno-strict-overflow',
515 '-Wno-unused-parameter',
516 '-Wno-missing-field-initializers',
517 '-Wno-write-strings',
518 '-Wno-unknown-pragmas',
520 '-Wno-deprecated-declarations',
524 '-fno-strict-aliasing',
528 '-Wno-missing-braces',
530 if check_env_flag(
'WERROR'):
531 extra_compile_args.append(
'-Werror')
533 library_dirs.append(lib_path)
538 CAFFE2_LIBS.extend([
'-Wl,--no-as-needed', os.path.join(lib_path,
'libcaffe2_gpu.so'),
'-Wl,--as-needed'])
540 CAFFE2_LIBS.extend([
'-Wl,--no-as-needed', os.path.join(lib_path,
'libcaffe2_hip.so'),
'-Wl,--as-needed'])
546 CAFFE2_LIBS.append(os.path.join(lib_path,
'libcaffe2_gpu.dylib'))
548 CAFFE2_LIBS.append(os.path.join(lib_path,
'libcaffe2_hip.dylib'))
553 CAFFE2_LIBS.append(os.path.join(lib_path,
'caffe2_gpu.lib'))
555 CAFFE2_LIBS.append(os.path.join(lib_path,
'caffe2_hip.lib'))
557 main_compile_args = []
558 main_libraries = [
'shm',
'torch_python']
560 main_sources = [
"torch/csrc/stub.cpp"]
575 main_link_args.extend(CAFFE2_LIBS)
579 NUMPY_INCLUDE_DIR = np.get_include()
586 cuda_lib_path = CUDA_HOME +
'/lib/x64/' 588 cuda_lib_dirs = [
'lib64',
'lib']
589 for lib_dir
in cuda_lib_dirs:
590 cuda_lib_path = os.path.join(CUDA_HOME, lib_dir)
591 if os.path.exists(cuda_lib_path):
593 library_dirs.append(cuda_lib_path)
597 extra_link_args.append(
'/DEBUG:FULL')
599 extra_compile_args += [
'-O0',
'-g']
600 extra_link_args += [
'-O0',
'-g']
602 if REL_WITH_DEB_INFO:
604 extra_link_args.append(
'/DEBUG:FULL')
606 extra_compile_args += [
'-g']
607 extra_link_args += [
'-g']
610 def make_relative_rpath(path):
612 return '-Wl,-rpath,@loader_path/' + path
616 return '-Wl,-rpath,$ORIGIN/' + path
623 packages = find_packages(exclude=(
'tools',
'tools.*'))
624 C = Extension(
"torch._C",
625 libraries=main_libraries,
626 sources=main_sources,
628 extra_compile_args=main_compile_args + extra_compile_args,
630 library_dirs=library_dirs,
631 extra_link_args=extra_link_args + main_link_args + [make_relative_rpath(
'lib')],
636 DL = Extension(
"torch._dl",
637 sources=[
"torch/csrc/dl.c"],
640 extensions.append(DL)
646 name=str(
'caffe2.python.caffe2_pybind11_state'),
652 name=str(
'caffe2.python.caffe2_pybind11_state_gpu'),
658 name=str(
'caffe2.python.caffe2_pybind11_state_hip'),
663 'build_ext': build_ext,
670 'convert-caffe2-to-onnx = caffe2.python.onnx.bin.conversion:caffe2_to_onnx',
671 'convert-onnx-to-caffe2 = caffe2.python.onnx.bin.conversion:onnx_to_caffe2',
676 build_update_message =
""" 677 It is no longer necessary to use the 'build' or 'rebuild' targets 680 $ python setup.py install 682 $ python setup.py develop 683 To force cmake to re-run (off by default): 684 $ python setup.py develop --cmake 689 lines = msg.split(
'\n')
690 size = max(len(l) + 1
for l
in lines)
691 print(
'-' * (size + 2))
693 print(
'|{}{}|'.format(l,
' ' * (size - len(l))))
694 print(
'-' * (size + 2))
696 if __name__ ==
'__main__':
699 dist = Distribution()
700 dist.script_name = sys.argv[0]
701 dist.script_args = sys.argv[1:]
703 ok = dist.parse_command_line()
704 except DistutilsArgError
as msg:
705 raise SystemExit(core.gen_usage(dist.script_name) +
"\nerror: %s" % msg)
714 description=(
"Tensors and Dynamic neural networks in " 715 "Python with strong GPU acceleration"),
716 ext_modules=extensions,
719 entry_points=entry_points,
730 'lib/torch_shm_manager',
733 'include/ATen/cpu/*.h',
734 'include/ATen/cpu/vec256/*.h',
735 'include/ATen/core/*.h',
736 'include/ATen/cuda/*.cuh',
737 'include/ATen/cuda/*.h',
738 'include/ATen/cuda/detail/*.cuh',
739 'include/ATen/cuda/detail/*.h',
740 'include/ATen/cudnn/*.h',
741 'include/ATen/detail/*.h',
742 'include/caffe2/utils/*.h',
744 'include/c10/macros/*.h',
745 'include/c10/core/*.h',
746 'include/ATen/core/dispatch/*.h',
747 'include/c10/core/impl/*.h',
748 'include/ATen/core/opschema/*.h',
749 'include/c10/util/*.h',
750 'include/c10/cuda/*.h',
751 'include/c10/cuda/impl/*.h',
752 'include/c10/hip/*.h',
753 'include/c10/hip/impl/*.h',
754 'include/caffe2/**/*.h',
756 'include/torch/csrc/*.h',
757 'include/torch/csrc/api/include/torch/*.h',
758 'include/torch/csrc/api/include/torch/data/*.h',
759 'include/torch/csrc/api/include/torch/data/dataloader/*.h',
760 'include/torch/csrc/api/include/torch/data/datasets/*.h',
761 'include/torch/csrc/api/include/torch/data/detail/*.h',
762 'include/torch/csrc/api/include/torch/data/samplers/*.h',
763 'include/torch/csrc/api/include/torch/data/transforms/*.h',
764 'include/torch/csrc/api/include/torch/detail/*.h',
765 'include/torch/csrc/api/include/torch/detail/ordered_dict.h',
766 'include/torch/csrc/api/include/torch/nn/*.h',
767 'include/torch/csrc/api/include/torch/nn/modules/*.h',
768 'include/torch/csrc/api/include/torch/nn/parallel/*.h',
769 'include/torch/csrc/api/include/torch/optim/*.h',
770 'include/torch/csrc/api/include/torch/serialize/*.h',
771 'include/torch/csrc/autograd/*.h',
772 'include/torch/csrc/autograd/functions/*.h',
773 'include/torch/csrc/autograd/generated/*.h',
774 'include/torch/csrc/autograd/utils/*.h',
775 'include/torch/csrc/cuda/*.h',
776 'include/torch/csrc/jit/*.h',
777 'include/torch/csrc/jit/generated/*.h',
778 'include/torch/csrc/jit/passes/*.h',
779 'include/torch/csrc/jit/script/*.h',
780 'include/torch/csrc/jit/testing/*.h',
781 'include/torch/csrc/onnx/*.h',
782 'include/torch/csrc/utils/*.h',
783 'include/pybind11/*.h',
784 'include/pybind11/detail/*.h',
786 'include/TH/generic/*.h*',
789 'include/THC/generic/*.h',
790 'include/THCUNN/*.cuh',
791 'include/THCUNN/generic/*.h',
793 'include/THNN/generic/*.h',
794 'share/cmake/ATen/*.cmake',
795 'share/cmake/Caffe2/*.cmake',
796 'share/cmake/Caffe2/public/*.cmake',
797 'share/cmake/Caffe2/Modules_CUDA_fix/*.cmake',
798 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/*.cmake',
799 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/*.cmake',
800 'share/cmake/Gloo/*.cmake',
801 'share/cmake/Torch/*.cmake',
804 'python/serialized_test/data/operator_test/*.zip',
808 if EMIT_BUILD_WARNING:
809 print_box(build_update_message)
def create_compile_commands(self)