172from __future__
import print_function
174if sys.version_info < (3,):
175 print(
"Python 2 has reached end-of-life and is no longer supported by PyTorch.")
177if sys.platform ==
'win32' and sys.maxsize.bit_length() == 31:
178 print(
"32-bit Windows Python runtime is not supported. Please switch to 64-bit Python.")
182python_min_version = (3, 6, 2)
183python_min_version_str =
'.'.
join(
map(str, python_min_version))
184if sys.version_info < python_min_version:
185 print(
"You are using Python {}. Python >={} is required.".
format(platform.python_version(),
186 python_min_version_str))
189from setuptools
import setup, Extension, find_packages
190from collections
import defaultdict
191from distutils
import core
192from distutils.core
import Distribution
193from distutils.errors
import DistutilsArgError
197import distutils.sysconfig
208 check_env_flag, build_type)
220EMIT_BUILD_WARNING =
False
228 if arg ==
'--cmake-only':
233 if arg ==
'rebuild' or arg ==
'build':
235 EMIT_BUILD_WARNING =
True
237 filtered_args += sys.argv[i:]
239 if arg ==
'-q' or arg ==
'--quiet':
240 VERBOSE_SCRIPT =
False
241 if arg ==
'clean' or arg ==
'egg_info':
242 RUN_BUILD_DEPS =
False
243 filtered_args.append(arg)
244sys.argv = filtered_args
254cwd = os.path.dirname(os.path.abspath(__file__))
255lib_path = os.path.join(cwd,
"torch",
"lib")
256third_party_path = os.path.join(cwd,
"third_party")
257caffe2_build_dir = os.path.join(cwd,
"build")
259rel_site_packages = distutils.sysconfig.get_python_lib(prefix=
'')
261full_site_packages = distutils.sysconfig.get_python_lib()
264 cmake_python_library =
"{}/libs/python{}.lib".
format(
265 distutils.sysconfig.get_config_var(
"prefix"),
266 distutils.sysconfig.get_config_var(
"VERSION"))
269 if not os.path.exists(cmake_python_library):
270 cmake_python_library =
"{}/libs/python{}.lib".
format(
272 distutils.sysconfig.get_config_var(
"VERSION"))
274 cmake_python_library =
"{}/{}".
format(
275 distutils.sysconfig.get_config_var(
"LIBDIR"),
276 distutils.sysconfig.get_config_var(
"INSTSONAME"))
277cmake_python_include_dir = distutils.sysconfig.get_python_inc()
283package_name = os.getenv(
'TORCH_PACKAGE_NAME',
'torch')
285report(
"Building wheel {}-{}".
format(package_name, version))
291 report(
'-- Building version ' + version)
294 if bool(os.getenv(
"USE_SYSTEM_LIBS",
False)):
296 if not os.path.exists(f):
298 report(
"Did you run 'git submodule update --init --recursive'?")
301 check_file(os.path.join(third_party_path,
"gloo",
"CMakeLists.txt"))
302 check_file(os.path.join(third_party_path,
'cpuinfo',
'CMakeLists.txt'))
303 check_file(os.path.join(third_party_path,
'tbb',
'Makefile'))
304 check_file(os.path.join(third_party_path,
'onnx',
'CMakeLists.txt'))
305 check_file(os.path.join(third_party_path,
'foxi',
'CMakeLists.txt'))
306 check_file(os.path.join(third_party_path,
'QNNPACK',
'CMakeLists.txt'))
307 check_file(os.path.join(third_party_path,
'fbgemm',
'CMakeLists.txt'))
308 check_file(os.path.join(third_party_path,
'fbgemm',
'third_party',
309 'asmjit',
'CMakeLists.txt'))
310 check_file(os.path.join(third_party_path,
'onnx',
'third_party',
311 'benchmark',
'CMakeLists.txt'))
316 cmake_python_library=cmake_python_library,
318 rerun_cmake=RERUN_CMAKE,
319 cmake_only=CMAKE_ONLY,
323 report(
'Finished running cmake. Run "ccmake build" or '
324 '"cmake-gui build" to adjust build options and '
325 '"python setup.py install" to build.')
331 'tools/shared/_utils_internal.py',
332 'torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h',
333 'torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h',
336 'torch/_utils_internal.py',
337 'third_party/valgrind-headers/callgrind.h',
338 'third_party/valgrind-headers/valgrind.h',
340 for sym_file, orig_file
in zip(sym_files, orig_files):
342 if os.path.exists(sym_file):
343 if filecmp.cmp(sym_file, orig_file):
348 shutil.copyfile(orig_file, sym_file)
357 'dataclasses; python_version < "3.7"'
361Missing build dependency: Unable to `import {importname}`.
362Please install it via `conda install {module}` or `pip install {module}`
368 importlib.import_module(importname)
370 raise RuntimeError(missing_pydep.format(importname=importname, module=module))
379 lib_dir = os.path.join(self.build_lib,
'torch',
'lib')
380 libtorch_cpu_path = os.path.join(lib_dir,
'libtorch_cpu.dylib')
381 if not os.path.exists(libtorch_cpu_path):
384 otool_cmds = subprocess.check_output([
'otool',
'-l', libtorch_cpu_path]).decode(
'utf-8').
split(
'\n')
385 rpaths, libs = [], []
387 if line.strip() ==
'cmd LC_LOAD_DYLIB':
388 lib_name = otool_cmds[idx + 2].strip()
389 assert lib_name.startswith(
'name ')
390 libs.append(lib_name.split(
' ', 1)[1].rsplit(
'(', 1)[0][:-1])
392 if line.strip() ==
'cmd LC_RPATH':
393 rpath = otool_cmds[idx + 2].strip()
394 assert rpath.startswith(
'path ')
395 rpaths.append(rpath.split(
' ', 1)[1].rsplit(
'(', 1)[0][:-1])
397 omp_lib_name =
'libiomp5.dylib'
398 if os.path.join(
'@rpath', omp_lib_name)
not in libs:
403 source_lib = os.path.join(rpath, omp_lib_name)
404 if not os.path.exists(source_lib):
406 target_lib = os.path.join(self.build_lib,
'torch',
'lib', omp_lib_name)
407 self.copy_file(source_lib, target_lib)
413 cmake_cache_vars =
defaultdict(
lambda:
False, cmake.get_cmake_cache_variables())
414 if cmake_cache_vars[
'USE_NUMPY']:
415 report(
'-- Building with NumPy bindings')
417 report(
'-- NumPy not found')
418 if cmake_cache_vars[
'USE_CUDNN']:
419 report(
'-- Detected cuDNN at ' +
420 cmake_cache_vars[
'CUDNN_LIBRARY'] +
', ' + cmake_cache_vars[
'CUDNN_INCLUDE_DIR'])
422 report(
'-- Not using cuDNN')
423 if cmake_cache_vars[
'USE_CUDA']:
424 report(
'-- Detected CUDA at ' + cmake_cache_vars[
'CUDA_TOOLKIT_ROOT_DIR'])
426 report(
'-- Not using CUDA')
427 if cmake_cache_vars[
'USE_MKLDNN']:
429 if cmake_cache_vars[
'USE_MKLDNN_CBLAS']:
430 report(
'-- Using CBLAS in MKLDNN')
432 report(
'-- Not using CBLAS in MKLDNN')
434 report(
'-- Not using MKLDNN')
435 if cmake_cache_vars[
'USE_NCCL']
and cmake_cache_vars[
'USE_SYSTEM_NCCL']:
436 report(
'-- Using system provided NCCL library at {}, {}'.
format(cmake_cache_vars[
'NCCL_LIBRARIES'],
437 cmake_cache_vars[
'NCCL_INCLUDE_DIRS']))
438 elif cmake_cache_vars[
'USE_NCCL']:
439 report(
'-- Building NCCL library')
441 report(
'-- Not using NCCL')
442 if cmake_cache_vars[
'USE_DISTRIBUTED']:
444 report(
'-- Building without distributed package')
446 report(
'-- Building with distributed package ')
448 report(
'-- Building without distributed package')
452 system_c_flags = distutils.sysconfig.get_config_var(
'CFLAGS')
453 if IS_LINUX
and '-fstack-clash-protection' in system_c_flags
and 'clang' in os.environ.get(
'CC',
''):
454 os.environ[
'CC'] = distutils.sysconfig.get_config_var(
'CC')
457 setuptools.command.build_ext.build_ext.run(self)
463 build_temp = self.build_temp
465 ext_filename = self.get_ext_filename(
'_C')
466 lib_filename =
'.'.
join(ext_filename.split(
'.')[:-1]) +
'.lib'
468 export_lib = os.path.join(
469 build_temp,
'torch',
'csrc', lib_filename).
replace(
'\\',
'/')
471 build_lib = self.build_lib
473 target_lib = os.path.join(
474 build_lib,
'torch',
'lib',
'_C.lib').
replace(
'\\',
'/')
478 target_dir = os.path.dirname(target_lib)
479 if not os.path.exists(target_dir):
480 os.makedirs(target_dir)
482 self.copy_file(export_lib, target_lib)
493 caffe2_pybind_exts = [
494 'caffe2.python.caffe2_pybind11_state',
495 'caffe2.python.caffe2_pybind11_state_gpu',
496 'caffe2.python.caffe2_pybind11_state_hip',
499 while i <
len(self.extensions):
500 ext = self.extensions[i]
501 if ext.name
not in caffe2_pybind_exts:
504 fullname = self.get_ext_fullname(ext.name)
505 filename = self.get_ext_filename(fullname)
508 src = os.path.join(
"torch", rel_site_packages, filename)
509 if not os.path.exists(src):
511 del self.extensions[i]
513 dst = os.path.join(os.path.realpath(self.build_lib), filename)
514 report(
"Copying {} from {} to {}".
format(ext.name, src, dst))
515 dst_dir = os.path.dirname(dst)
516 if not os.path.exists(dst_dir):
518 self.copy_file(src, dst)
520 distutils.command.build_ext.build_ext.build_extensions(self)
523 outputs = distutils.command.build_ext.build_ext.get_outputs(self)
524 outputs.append(os.path.join(self.build_lib,
"caffe2"))
525 report(
"setup.py::get_outputs returning {}".
format(outputs))
530 with open(filename)
as f:
532 ninja_files = glob.glob(
'build/*compile_commands.json')
533 cmake_files = glob.glob(
'torch/lib/build/*/compile_commands.json')
534 all_commands = [entry
535 for f
in ninja_files + cmake_files
536 for entry
in load(f)]
542 for command
in all_commands:
543 if command[
'command'].startswith(
"gcc "):
544 command[
'command'] =
"g++ " + command[
'command'][4:]
546 new_contents = json.dumps(all_commands, indent=2)
548 if os.path.exists(
'compile_commands.json'):
549 with open(
'compile_commands.json',
'r')
as f:
551 if contents != new_contents:
552 with open(
'compile_commands.json',
'w')
as f:
553 f.write(new_contents)
556 """Merge LICENSE and LICENSES_BUNDLED.txt as a context manager
558 LICENSE is the main PyTorch license, LICENSES_BUNDLED.txt
is auto-generated
559 from all the licenses found
in ./third_party/. We concatenate them so there
560 is a single license file
in the sdist
and wheels
with all of the necessary
564 self.
f1f1 =
'LICENSE'
565 self.
f2f2 =
'third_party/LICENSES_BUNDLED.txt'
568 """Concatenate files"""
569 with open(self.
f1f1,
'r')
as f1:
572 with open(self.
f1f1,
'a')
as f1:
573 with open(self.
f2f2,
'r')
as f2:
578 def __exit__(self, exception_type, exception_value, traceback):
579 """Restore content of f1"""
580 with open(self.
f1f1,
'w')
as f:
585 from wheel.bdist_wheel
import bdist_wheel
590 wheel_concatenate =
None
594 """ check submodules on sdist to prevent incomplete tarballs """
600class install(setuptools.command.install.install):
602 setuptools.command.install.install.run(self)
605class clean(distutils.command.clean.clean):
609 with open(
'.gitignore',
'r')
as f:
611 pat = re.compile(
r'^#( BEGIN NOT-CLEAN-FILES )?')
612 for wildcard
in filter(
None, ignores.split(
'\n')):
613 match = pat.match(wildcard)
620 for filename
in glob.glob(wildcard):
624 shutil.rmtree(filename, ignore_errors=
True)
627 distutils.command.clean.clean.run(self)
630 r"""Configures extension build options according to system environment and user's choice.
633 The input to parameters ext_modules, cmdclass, packages, and entry_points
as required
in setuptools.setup.
637 cmake_cache_vars =
defaultdict(
lambda:
False, cmake.get_cmake_cache_variables())
638 except FileNotFoundError:
647 extra_install_requires = []
652 extra_link_args = [
'/NODEFAULTLIB:LIBCMT.LIB']
658 extra_compile_args = [
'/MD',
'/EHsc',
'/DNOMINMAX',
659 '/wd4267',
'/wd4251',
'/wd4522',
'/wd4522',
'/wd4838',
660 '/wd4305',
'/wd4244',
'/wd4190',
'/wd4101',
'/wd4996',
664 extra_compile_args = [
667 '-Wno-strict-overflow',
668 '-Wno-unused-parameter',
669 '-Wno-missing-field-initializers',
670 '-Wno-write-strings',
671 '-Wno-unknown-pragmas',
673 '-Wno-deprecated-declarations',
677 '-fno-strict-aliasing',
681 '-Wno-missing-braces',
684 extra_compile_args.append(
'-Werror')
686 library_dirs.append(lib_path)
688 main_compile_args = []
689 main_libraries = [
'torch_python']
691 main_sources = [
"torch/csrc/stub.c"]
693 if cmake_cache_vars[
'USE_CUDA']:
695 os.path.dirname(cmake_cache_vars[
'CUDA_CUDA_LIB']))
697 if cmake_cache_vars[
'USE_NUMPY']:
698 extra_install_requires += [
'numpy']
700 if build_type.is_debug():
702 extra_compile_args.append(
'/Z7')
703 extra_link_args.append(
'/DEBUG:FULL')
705 extra_compile_args += [
'-O0',
'-g']
706 extra_link_args += [
'-O0',
'-g']
708 if build_type.is_rel_with_deb_info():
710 extra_compile_args.append(
'/Z7')
711 extra_link_args.append(
'/DEBUG:FULL')
713 extra_compile_args += [
'-g']
714 extra_link_args += [
'-g']
717 def make_relative_rpath_args(path):
719 return [
'-Wl,-rpath,@loader_path/' + path]
723 return [
'-Wl,-rpath,$ORIGIN/' + path]
730 packages = find_packages(exclude=(
'tools',
'tools.*'))
731 C = Extension(
"torch._C",
732 libraries=main_libraries,
733 sources=main_sources,
735 extra_compile_args=main_compile_args + extra_compile_args,
737 library_dirs=library_dirs,
738 extra_link_args=extra_link_args + main_link_args + make_relative_rpath_args(
'lib'))
742 DL = Extension(
"torch._dl",
743 sources=[
"torch/csrc/dl.c"],
745 extensions.append(DL)
751 name=
str(
'caffe2.python.caffe2_pybind11_state'),
754 if cmake_cache_vars[
'USE_CUDA']:
757 name=
str(
'caffe2.python.caffe2_pybind11_state_gpu'),
760 if cmake_cache_vars[
'USE_ROCM']:
763 name=
str(
'caffe2.python.caffe2_pybind11_state_hip'),
768 'build_ext': build_ext,
771 'bdist_wheel': wheel_concatenate,
776 'convert-caffe2-to-onnx = caffe2.python.onnx.bin.conversion:caffe2_to_onnx',
777 'convert-onnx-to-caffe2 = caffe2.python.onnx.bin.conversion:onnx_to_caffe2',
781 return extensions, cmdclass, packages, entry_points, extra_install_requires
784build_update_message =
"""
785 It is no longer necessary to use the
'build' or 'rebuild' targets
788 $ python setup.py install
790 $ python setup.py develop
791 To force cmake to re-generate native build files (off by default):
792 $ python setup.py develop --cmake
797 lines = msg.split('\n')
798 size =
max(
len(l) + 1
for l
in lines)
799 print(
'-' * (size + 2))
802 print(
'-' * (size + 2))
804if __name__ ==
'__main__':
807 dist = Distribution()
808 dist.script_name = sys.argv[0]
809 dist.script_args = sys.argv[1:]
811 ok = dist.parse_command_line()
812 except DistutilsArgError
as msg:
813 raise SystemExit(core.gen_usage(dist.script_name) +
"\nerror: %s" % msg)
822 install_requires += extra_install_requires
825 with open(os.path.join(cwd,
"README.md"), encoding=
"utf-8")
as f:
826 long_description = f.read()
828 version_range_max =
max(sys.version_info[1], 8) + 1
832 description=(
"Tensors and Dynamic neural networks in "
833 "Python with strong GPU acceleration"),
834 long_description=long_description,
835 long_description_content_type=
"text/markdown",
836 ext_modules=extensions,
839 entry_points=entry_points,
840 install_requires=install_requires,
859 'lib/torch_shm_manager',
862 'include/ATen/cpu/*.h',
863 'include/ATen/cpu/vec256/*.h',
864 'include/ATen/core/*.h',
865 'include/ATen/cuda/*.cuh',
866 'include/ATen/cuda/*.h',
867 'include/ATen/cuda/detail/*.cuh',
868 'include/ATen/cuda/detail/*.h',
869 'include/ATen/cudnn/*.h',
870 'include/ATen/hip/*.cuh',
871 'include/ATen/hip/*.h',
872 'include/ATen/hip/detail/*.cuh',
873 'include/ATen/hip/detail/*.h',
874 'include/ATen/hip/impl/*.h',
875 'include/ATen/detail/*.h',
876 'include/ATen/native/*.h',
877 'include/ATen/native/cpu/*.h',
878 'include/ATen/native/cuda/*.h',
879 'include/ATen/native/cuda/*.cuh',
880 'include/ATen/native/hip/*.h',
881 'include/ATen/native/hip/*.cuh',
882 'include/ATen/native/quantized/*.h',
883 'include/ATen/native/quantized/cpu/*.h',
884 'include/ATen/quantized/*.h',
885 'include/caffe2/utils/*.h',
886 'include/caffe2/utils/**/*.h',
888 'include/c10/macros/*.h',
889 'include/c10/core/*.h',
890 'include/ATen/core/boxing/*.h',
891 'include/ATen/core/boxing/impl/*.h',
892 'include/ATen/core/dispatch/*.h',
893 'include/ATen/core/op_registration/*.h',
894 'include/c10/core/impl/*.h',
895 'include/c10/util/*.h',
896 'include/c10/cuda/*.h',
897 'include/c10/cuda/impl/*.h',
898 'include/c10/hip/*.h',
899 'include/c10/hip/impl/*.h',
900 'include/c10d/*.hpp',
901 'include/caffe2/**/*.h',
903 'include/torch/csrc/*.h',
904 'include/torch/csrc/api/include/torch/*.h',
905 'include/torch/csrc/api/include/torch/data/*.h',
906 'include/torch/csrc/api/include/torch/data/dataloader/*.h',
907 'include/torch/csrc/api/include/torch/data/datasets/*.h',
908 'include/torch/csrc/api/include/torch/data/detail/*.h',
909 'include/torch/csrc/api/include/torch/data/samplers/*.h',
910 'include/torch/csrc/api/include/torch/data/transforms/*.h',
911 'include/torch/csrc/api/include/torch/detail/*.h',
912 'include/torch/csrc/api/include/torch/detail/ordered_dict.h',
913 'include/torch/csrc/api/include/torch/nn/*.h',
914 'include/torch/csrc/api/include/torch/nn/functional/*.h',
915 'include/torch/csrc/api/include/torch/nn/options/*.h',
916 'include/torch/csrc/api/include/torch/nn/modules/*.h',
917 'include/torch/csrc/api/include/torch/nn/modules/container/*.h',
918 'include/torch/csrc/api/include/torch/nn/parallel/*.h',
919 'include/torch/csrc/api/include/torch/nn/utils/*.h',
920 'include/torch/csrc/api/include/torch/optim/*.h',
921 'include/torch/csrc/api/include/torch/serialize/*.h',
922 'include/torch/csrc/autograd/*.h',
923 'include/torch/csrc/autograd/functions/*.h',
924 'include/torch/csrc/autograd/generated/*.h',
925 'include/torch/csrc/autograd/utils/*.h',
926 'include/torch/csrc/cuda/*.h',
927 'include/torch/csrc/jit/*.h',
928 'include/torch/csrc/jit/backends/*.h',
929 'include/torch/csrc/jit/generated/*.h',
930 'include/torch/csrc/jit/passes/*.h',
931 'include/torch/csrc/jit/passes/quantization/*.h',
932 'include/torch/csrc/jit/passes/utils/*.h',
933 'include/torch/csrc/jit/runtime/*.h',
934 'include/torch/csrc/jit/ir/*.h',
935 'include/torch/csrc/jit/frontend/*.h',
936 'include/torch/csrc/jit/api/*.h',
937 'include/torch/csrc/jit/serialization/*.h',
938 'include/torch/csrc/jit/python/*.h',
939 'include/torch/csrc/jit/testing/*.h',
940 'include/torch/csrc/jit/tensorexpr/*.h',
941 'include/torch/csrc/onnx/*.h',
942 'include/torch/csrc/utils/*.h',
943 'include/pybind11/*.h',
944 'include/pybind11/detail/*.h',
946 'include/TH/generic/*.h*',
949 'include/THC/generic/*.h',
950 'include/THCUNN/*.cuh',
951 'include/THCUNN/generic/*.h',
954 'include/THH/generic/*.h',
955 'share/cmake/ATen/*.cmake',
956 'share/cmake/Caffe2/*.cmake',
957 'share/cmake/Caffe2/public/*.cmake',
958 'share/cmake/Caffe2/Modules_CUDA_fix/*.cmake',
959 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/*.cmake',
960 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/*.cmake',
961 'share/cmake/Gloo/*.cmake',
962 'share/cmake/Tensorpipe/*.cmake',
963 'share/cmake/Torch/*.cmake',
964 'utils/benchmark/utils/*.cpp',
965 'utils/benchmark/utils/valgrind_wrapper/*.cpp',
966 'utils/benchmark/utils/valgrind_wrapper/*.h',
969 'python/serialized_test/data/operator_test/*.zip',
972 url=
'https://pytorch.org/',
973 download_url=
'https://github.com/pytorch/pytorch/tags',
974 author=
'PyTorch Team',
975 author_email=
'packages@pytorch.org',
976 python_requires=
'>={}'.
format(python_min_version_str),
979 'Development Status :: 5 - Production/Stable',
980 'Intended Audience :: Developers',
981 'Intended Audience :: Education',
982 'Intended Audience :: Science/Research',
983 'License :: OSI Approved :: BSD License',
984 'Topic :: Scientific/Engineering',
985 'Topic :: Scientific/Engineering :: Mathematics',
986 'Topic :: Scientific/Engineering :: Artificial Intelligence',
987 'Topic :: Software Development',
988 'Topic :: Software Development :: Libraries',
989 'Topic :: Software Development :: Libraries :: Python Modules',
990 'Programming Language :: C++',
991 'Programming Language :: Python :: 3',
992 ] + [
'Programming Language :: Python :: 3.{}'.
format(i)
for i
in range(python_min_version[1], version_range_max)],
994 keywords=
'pytorch machine learning',
996 if EMIT_BUILD_WARNING:
def build_extensions(self)
def create_compile_commands(self)
def __exit__(self, exception_type, exception_value, traceback)
void map(const Op &vec_fun, scalar_t *output_data, const scalar_t *input_data, int64_t size)
std::ostream & print(std::ostream &stream, const Tensor &tensor_, int64_t linesize)
constexpr Symbol format(static_cast< unique_t >(_keys::aten_format))
constexpr Symbol len(static_cast< unique_t >(_keys::aten_len))
constexpr Symbol enumerate(static_cast< unique_t >(_keys::prim_enumerate))
constexpr Symbol zip(static_cast< unique_t >(_keys::prim_zip))
constexpr Symbol range(static_cast< unique_t >(_keys::prim_range))
std::string replace(std::string line, const std::string &substring, const std::string &target)
INT_MAX Subnet with blob bindings Indices of corresponding outer workspace in List of blobs from the forward Do int out bool
this is done throughout the image data and the output is computed As a side note on the implementation which is why they are separate files DOC filter
def configure_extension_build()
def check_pydep(importname, module)
Module caffe2.python.layers.split.