blob: aa1669a10d309cd3531b1aaf1e8c686f5530105e [file] [log] [blame]
Edward Z. Yang031412a2018-02-20 16:55:57 -05001# Welcome to the PyTorch setup.py.
2#
srib53d26122018-04-16 14:29:45 -05003# Environment variables you are probably interested in:
Edward Z. Yang031412a2018-02-20 16:55:57 -05004#
5# DEBUG
6# build with -O0 and -g (debug symbols)
7#
Zachary DeVito788d2e82018-11-21 06:36:26 -08008# REL_WITH_DEB_INFO
9# build with optimizations and -g (debug symbols)
10#
Edward Z. Yang031412a2018-02-20 16:55:57 -050011# MAX_JOBS
12# maximum number of compile jobs we should use to compile your code
13#
Soumith Chintala3069c452019-02-21 09:53:24 -080014# USE_CUDA=0
Edward Z. Yang031412a2018-02-20 16:55:57 -050015# disables CUDA build
16#
17# CFLAGS
18# flags to apply to both C and C++ files to be compiled (a quirk of setup.py
19# which we have faithfully adhered to in our build system is that CFLAGS
Hong Xu1a9334e2019-08-07 16:18:12 -070020# also applies to C++ files (unless CXXFLAGS is set), in contrast to the
21# default behavior of autogoo and cmake build systems.)
Edward Z. Yang031412a2018-02-20 16:55:57 -050022#
23# CC
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -070024# the C/C++ compiler to use
Edward Z. Yang031412a2018-02-20 16:55:57 -050025#
26# Environment variables for feature toggles:
27#
Soumith Chintala3069c452019-02-21 09:53:24 -080028# USE_CUDNN=0
Edward Z. Yang031412a2018-02-20 16:55:57 -050029# disables the cuDNN build
30#
Soumith Chintala3069c452019-02-21 09:53:24 -080031# USE_FBGEMM=0
Daya S Khudia18de3302018-11-06 15:37:30 -080032# disables the FBGEMM build
33#
Ilia Cherniavskiie34992e2021-01-22 00:06:18 -080034# USE_KINETO=0
35# disables usage of libkineto library for profiling
Ilia Cherniavskiif2da18a2020-11-21 20:18:40 -080036#
Hong Xu240d62f2019-06-06 08:11:17 -070037# USE_NUMPY=0
38# disables the NumPy build
39#
Vishwak Srinivasan9e697032019-02-22 17:03:49 -080040# BUILD_TEST=0
Orion Reblitz-Richardson802d21c2018-09-07 15:06:30 -070041# disables the test build
42#
Soumith Chintala3069c452019-02-21 09:53:24 -080043# USE_MKLDNN=0
Gu, Jinghuid01cb702018-11-08 11:16:33 -080044# disables use of MKLDNN
45#
Nathan John Sircombebf00d262021-05-20 07:42:48 -070046# USE_MKLDNN_ACL
47# enables use of Compute Library backend for MKLDNN on Arm;
48# USE_MKLDNN must be explicitly enabled.
49#
pinzhenxbd604cb2020-03-26 22:01:21 -070050# MKLDNN_CPU_RUNTIME
Ilia Cherniavskii74f80942019-07-26 13:05:54 -070051# MKL-DNN threading mode: TBB or OMP (default)
Ilia Cherniavskii481b6d02019-05-06 19:25:55 -070052#
Soumith Chintala3069c452019-02-21 09:53:24 -080053# USE_NNPACK=0
Edward Z. Yang031412a2018-02-20 16:55:57 -050054# disables NNPACK build
55#
Soumith Chintala3069c452019-02-21 09:53:24 -080056# USE_QNNPACK=0
Marat Dukhan5e73b822018-10-25 22:13:18 -070057# disables QNNPACK build (quantized 8-bit operators)
58#
Soumith Chintala3069c452019-02-21 09:53:24 -080059# USE_DISTRIBUTED=0
Orion Reblitz-Richardsondda84022018-09-06 08:40:57 -070060# disables distributed (c10d, gloo, mpi, etc.) build
Edward Z. Yang031412a2018-02-20 16:55:57 -050061#
Rong Rong (AI Infra)f58f7b72021-03-05 14:37:24 -080062# USE_TENSORPIPE=0
63# disables distributed Tensorpipe backend build
64#
65# USE_GLOO=0
66# disables distributed gloo backend build
67#
68# USE_MPI=0
69# disables distributed MPI backend build
70#
Soumith Chintala3069c452019-02-21 09:53:24 -080071# USE_SYSTEM_NCCL=0
Edward Z. Yang031412a2018-02-20 16:55:57 -050072# disables use of system-wide nccl (we will use our submoduled
Edward Z. Yangeb18a2f2018-03-27 22:09:20 -040073# copy in third_party/nccl)
Edward Z. Yang031412a2018-02-20 16:55:57 -050074#
Vishwak Srinivasan9e697032019-02-22 17:03:49 -080075# BUILD_CAFFE2_OPS=0
Orion Reblitz-Richardsona1752822018-09-10 17:11:16 -070076# disable Caffe2 operators build
77#
Michael Suo18253f42020-10-01 14:56:59 -070078# BUILD_CAFFE2=0
79# disable Caffe2 build
80#
Hong Xu8a026d42019-09-10 04:31:31 -070081# USE_IBVERBS
Edward Z. Yang031412a2018-02-20 16:55:57 -050082# toggle features related to distributed support
83#
Orion Reblitz-Richardson802d21c2018-09-07 15:06:30 -070084# USE_OPENCV
85# enables use of OpenCV for additional operators
86#
Ilia Cherniavskii481b6d02019-05-06 19:25:55 -070087# USE_OPENMP=0
88# disables use of OpenMP for parallelization
89#
Orion Reblitz-Richardson25bd7fe2018-10-10 18:07:58 -070090# USE_FFMPEG
91# enables use of ffmpeg for additional operators
92#
Orion Reblitz-Richardsona1752822018-09-10 17:11:16 -070093# USE_LEVELDB
94# enables use of LevelDB for storage
95#
daquexian1fb89252018-10-03 06:03:02 -070096# USE_LMDB
Orion Reblitz-Richardsona1752822018-09-10 17:11:16 -070097# enables use of LMDB for storage
98#
Orion Reblitz-Richardson802d21c2018-09-07 15:06:30 -070099# BUILD_BINARY
100# enables the additional binaries/ build
101#
imaginary-person9e53c822021-07-22 08:49:55 -0700102# ATEN_AVX512_256=TRUE
103# ATen AVX2 kernels can use 32 ymm registers, instead of the default 16.
104# This option can be used if AVX512 doesn't perform well on a machine.
105# The FBGEMM library also uses AVX512_256 kernels on Xeon D processors,
106# but it also has some (optimized) assembly code.
107#
Edward Z. Yang031412a2018-02-20 16:55:57 -0500108# PYTORCH_BUILD_VERSION
109# PYTORCH_BUILD_NUMBER
110# specify the version of PyTorch, rather than the hard-coded version
111# in this file; used when we're building binaries for distribution
112#
Richard Zou7355f5c2018-04-02 13:35:14 -0400113# TORCH_CUDA_ARCH_LIST
114# specify which CUDA architectures to build for.
115# ie `TORCH_CUDA_ARCH_LIST="6.0;7.0"`
Edward Yangcd941632018-08-29 13:29:34 -0700116# These are not CUDA versions, instead, they specify what
117# classes of NVIDIA hardware we should generate PTX for.
Richard Zou7355f5c2018-04-02 13:35:14 -0400118#
Jithun Nair8dfdc3d2021-12-13 15:38:06 -0800119# PYTORCH_ROCM_ARCH
120# specify which AMD GPU targets to build for.
121# ie `PYTORCH_ROCM_ARCH="gfx900;gfx906"`
122#
Orion Reblitz-Richardsonedd4e2c2018-06-13 10:25:32 -0700123# ONNX_NAMESPACE
124# specify a namespace for ONNX built here rather than the hard-coded
125# one in this file; needed to build with other frameworks that share ONNX.
126#
Jesse Hellemn8964a2e62019-01-14 15:10:49 -0800127# BLAS
Robert Blackwellcee4e8f2021-10-28 11:23:00 -0700128# BLAS to be used by Caffe2. Can be MKL, Eigen, ATLAS, FlexiBLAS, or OpenBLAS. If set
Jesse Hellemn8964a2e62019-01-14 15:10:49 -0800129# then the build will fail if the requested BLAS is not found, otherwise
130# the BLAS will be chosen based on what is found on your system.
131#
Ilia Cherniavskii6350dbd2019-06-24 12:48:13 -0700132# MKL_THREADING
Ilia Cherniavskii74f80942019-07-26 13:05:54 -0700133# MKL threading mode: SEQ, TBB or OMP (default)
Ilia Cherniavskii481b6d02019-05-06 19:25:55 -0700134#
Jesse Hellemn8964a2e62019-01-14 15:10:49 -0800135# USE_REDIS
136# Whether to use Redis for distributed workflows (Linux only)
137#
138# USE_ZSTD
139# Enables use of ZSTD, if the libraries are found
140#
Edward Z. Yang031412a2018-02-20 16:55:57 -0500141# Environment variables we respect (these environment variables are
142# conventional and are often understood/set by other software.)
143#
144# CUDA_HOME (Linux/OS X)
145# CUDA_PATH (Windows)
146# specify where CUDA is installed; usually /usr/local/cuda or
147# /usr/local/cuda-x.y
Sven-Hendrik Haase080266e2018-10-03 06:20:46 -0700148# CUDAHOSTCXX
149# specify a different compiler than the system one to use as the CUDA
150# host compiler for nvcc.
Edward Z. Yang031412a2018-02-20 16:55:57 -0500151#
Jesse Hellemn8964a2e62019-01-14 15:10:49 -0800152# CUDA_NVCC_EXECUTABLE
153# Specify a NVCC to use. This is used in our CI to point to a cached nvcc
154#
Edward Z. Yang031412a2018-02-20 16:55:57 -0500155# CUDNN_LIB_DIR
156# CUDNN_INCLUDE_DIR
157# CUDNN_LIBRARY
158# specify where cuDNN is installed
159#
Johannes M Dietericha4c59a92018-08-23 15:20:02 -0700160# MIOPEN_LIB_DIR
161# MIOPEN_INCLUDE_DIR
162# MIOPEN_LIBRARY
163# specify where MIOpen is installed
164#
Hong Xu60c46dd2019-07-23 08:35:59 -0700165# NCCL_ROOT
Edward Z. Yang031412a2018-02-20 16:55:57 -0500166# NCCL_LIB_DIR
167# NCCL_INCLUDE_DIR
168# specify where nccl is installed
169#
170# NVTOOLSEXT_PATH (Windows only)
171# specify where nvtoolsext is installed
172#
Nathan John Sircombebf00d262021-05-20 07:42:48 -0700173# ACL_ROOT_DIR
174# specify where Compute Library is installed
175#
Edward Z. Yang031412a2018-02-20 16:55:57 -0500176# LIBRARY_PATH
177# LD_LIBRARY_PATH
178# we will search for libraries in these paths
Ilia Cherniavskiic3d05e82019-05-24 01:59:00 -0700179#
Ilia Cherniavskii74f80942019-07-26 13:05:54 -0700180# ATEN_THREADING
181# ATen parallel backend to use for intra- and inter-op parallelism
Ilia Cherniavskiic3d05e82019-05-24 01:59:00 -0700182# possible values:
Ilia Cherniavskii74f80942019-07-26 13:05:54 -0700183# OMP - use OpenMP for intra-op and native backend for inter-op tasks
Ilia Cherniavskii82aecfa2019-05-28 01:37:40 -0700184# NATIVE - use native thread pool for both intra- and inter-op tasks
Ilia Cherniavskii74f80942019-07-26 13:05:54 -0700185# TBB - using TBB for intra- and native thread pool for inter-op parallelism
Ilia Cherniavskii580eab62019-05-28 02:43:22 -0700186#
187# USE_TBB
Ilia Cherniavskii74f80942019-07-26 13:05:54 -0700188# enable TBB support
Ilia Cherniavskii580eab62019-05-28 02:43:22 -0700189#
Can Balioglu75650392021-08-02 07:37:57 -0700190# USE_SYSTEM_TBB
191# Use system-provided Intel TBB.
192#
Mo Zhouff21b152020-04-23 20:40:16 -0700193# USE_SYSTEM_LIBS (work in progress)
194# Use system-provided libraries to satisfy the build dependencies.
195# When turned on, the following cmake variables will be toggled as well:
196# USE_SYSTEM_CPUINFO=ON USE_SYSTEM_SLEEF=ON BUILD_CUSTOM_PROTOBUF=OFF
Edward Z. Yang031412a2018-02-20 16:55:57 -0500197
Nikita Shulgaa38eeef2020-10-14 16:30:39 -0700198# This future is needed to print Python2 EOL message
199from __future__ import print_function
David Reiss3c85f442020-04-16 10:18:08 -0700200import sys
201if sys.version_info < (3,):
Nikita Shulgaf00a37d2020-07-23 19:08:41 -0700202 print("Python 2 has reached end-of-life and is no longer supported by PyTorch.")
203 sys.exit(-1)
Shen Li10224432021-08-12 11:39:31 -0700204if sys.platform == 'win32' and sys.maxsize.bit_length() == 31:
205 print("32-bit Windows Python runtime is not supported. Please switch to 64-bit Python.")
Nikita Shulgaf00a37d2020-07-23 19:08:41 -0700206 sys.exit(-1)
David Reiss3c85f442020-04-16 10:18:08 -0700207
Hong Xu9063bce2020-08-28 09:03:02 -0700208import platform
Nikita Shulgadc5cda02022-01-19 15:59:11 -0800209python_min_version = (3, 7, 0)
Shen Li10224432021-08-12 11:39:31 -0700210python_min_version_str = '.'.join(map(str, python_min_version))
Nikita Shulga45de2ee2020-10-14 07:34:47 -0700211if sys.version_info < python_min_version:
Shen Li10224432021-08-12 11:39:31 -0700212 print("You are using Python {}. Python >={} is required.".format(platform.python_version(),
213 python_min_version_str))
Hong Xu9063bce2020-08-28 09:03:02 -0700214 sys.exit(-1)
215
Shen Li10224432021-08-12 11:39:31 -0700216from setuptools import setup, Extension, find_packages
Hong Xub811b6d2019-06-14 08:10:18 -0700217from collections import defaultdict
Shen Li10224432021-08-12 11:39:31 -0700218from setuptools.dist import Distribution
Adam Paszke207d6ae2016-08-14 20:47:27 -0700219import setuptools.command.build_ext
Adam Paszkeb06c0002016-08-16 21:02:46 -0700220import setuptools.command.install
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700221import setuptools.command.sdist
Shen Li10224432021-08-12 11:39:31 -0700222import filecmp
223import shutil
224import subprocess
225import os
226import json
227import glob
228import importlib
229import time
230import sysconfig
231
Zachary DeVito9477a5d2019-01-25 15:57:09 -0800232from tools.build_pytorch_libs import build_caffe2
Shen Li10224432021-08-12 11:39:31 -0700233from tools.setup_helpers.env import (IS_WINDOWS, IS_DARWIN, IS_LINUX,
234 build_type)
Zsolt Dollensteinb0043072021-08-12 10:56:55 -0700235from tools.setup_helpers.cmake import CMake
Shen Li10224432021-08-12 11:39:31 -0700236from tools.generate_torch_version import get_torch_version
Hong Xub811b6d2019-06-14 08:10:18 -0700237
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700238################################################################################
239# Parameters parsed from environment
240################################################################################
241
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800242VERBOSE_SCRIPT = True
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800243RUN_BUILD_DEPS = True
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800244# see if the user passed a quiet flag to setup.py arguments and respect
245# that in our parts of the build
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800246EMIT_BUILD_WARNING = False
Zachary DeVito9477a5d2019-01-25 15:57:09 -0800247RERUN_CMAKE = False
Hong Xu9a989ec2019-05-28 17:04:10 -0700248CMAKE_ONLY = False
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800249filtered_args = []
250for i, arg in enumerate(sys.argv):
Shen Li10224432021-08-12 11:39:31 -0700251 if arg == '--cmake':
Zachary DeVito9477a5d2019-01-25 15:57:09 -0800252 RERUN_CMAKE = True
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800253 continue
Shen Li10224432021-08-12 11:39:31 -0700254 if arg == '--cmake-only':
Hong Xu9a989ec2019-05-28 17:04:10 -0700255 # Stop once cmake terminates. Leave users a chance to adjust build
256 # options.
257 CMAKE_ONLY = True
258 continue
Shen Li10224432021-08-12 11:39:31 -0700259 if arg == 'rebuild' or arg == 'build':
260 arg = 'build' # rebuild is gone, make it build
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800261 EMIT_BUILD_WARNING = True
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800262 if arg == "--":
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800263 filtered_args += sys.argv[i:]
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800264 break
Shen Li10224432021-08-12 11:39:31 -0700265 if arg == '-q' or arg == '--quiet':
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800266 VERBOSE_SCRIPT = False
Shen Li10224432021-08-12 11:39:31 -0700267 if arg in ['clean', 'egg_info', 'sdist']:
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800268 RUN_BUILD_DEPS = False
269 filtered_args.append(arg)
270sys.argv = filtered_args
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800271
272if VERBOSE_SCRIPT:
273 def report(*args):
274 print(*args)
275else:
276 def report(*args):
277 pass
278
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700279 # Make distutils respect --quiet too
280 setuptools.distutils.log.warn = report
281
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700282# Constant known variables used throughout this file
283cwd = os.path.dirname(os.path.abspath(__file__))
284lib_path = os.path.join(cwd, "torch", "lib")
285third_party_path = os.path.join(cwd, "third_party")
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700286caffe2_build_dir = os.path.join(cwd, "build")
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700287
Philip Yangb57fdf12018-10-12 08:06:43 -0700288# CMAKE: full path to python library
CircleCIf1a2bc42018-11-12 14:35:39 -0800289if IS_WINDOWS:
290 cmake_python_library = "{}/libs/python{}.lib".format(
Shen Li10224432021-08-12 11:39:31 -0700291 sysconfig.get_config_var("prefix"),
292 sysconfig.get_config_var("VERSION"))
zrpherculec564d792019-12-05 13:21:43 -0800293 # Fix virtualenv builds
peterd05da7d2019-11-06 09:00:52 -0800294 # TODO: Fix for python < 3.3
295 if not os.path.exists(cmake_python_library):
296 cmake_python_library = "{}/libs/python{}.lib".format(
Shen Li10224432021-08-12 11:39:31 -0700297 sys.base_prefix,
298 sysconfig.get_config_var("VERSION"))
CircleCIf1a2bc42018-11-12 14:35:39 -0800299else:
300 cmake_python_library = "{}/{}".format(
Shen Li10224432021-08-12 11:39:31 -0700301 sysconfig.get_config_var("LIBDIR"),
302 sysconfig.get_config_var("INSTSONAME"))
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700303cmake_python_include_dir = sysconfig.get_path("include")
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700304
Soumith Chintala5e372c72018-06-06 12:53:58 -0400305
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700306################################################################################
Jesse Hellemndef37152018-08-10 11:55:03 -0700307# Version, create_version_file, and package_name
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700308################################################################################
Shen Li10224432021-08-12 11:39:31 -0700309package_name = os.getenv('TORCH_PACKAGE_NAME', 'torch')
Michael Suo161490d42020-09-16 15:39:56 -0700310version = get_torch_version()
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800311report("Building wheel {}-{}".format(package_name, version))
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700312
Hong Xu82545ec2019-07-25 07:16:01 -0700313cmake = CMake()
Soumith Chintala5e372c72018-06-06 12:53:58 -0400314
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700315
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800316def get_submodule_folders():
317 git_modules_path = os.path.join(cwd, ".gitmodules")
Shen Li10224432021-08-12 11:39:31 -0700318 default_modules_path = [os.path.join(third_party_path, name) for name in [
319 "gloo", "cpuinfo", "tbb", "onnx",
320 "foxi", "QNNPACK", "fbgemm"
321 ]]
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800322 if not os.path.exists(git_modules_path):
323 return default_modules_path
324 with open(git_modules_path) as f:
Shen Li10224432021-08-12 11:39:31 -0700325 return [os.path.join(cwd, line.split("=", 1)[1].strip()) for line in
326 f.readlines() if line.strip().startswith("path")]
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800327
328
Nikita Shulga272dfc72021-03-01 18:26:24 -0800329def check_submodules():
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800330 def check_for_files(folder, files):
331 if not any(os.path.exists(os.path.join(folder, f)) for f in files):
332 report("Could not find any of {} in {}".format(", ".join(files), folder))
zhouzhuojie6107cf32021-07-07 15:37:32 -0700333 report("Did you run 'git submodule update --init --recursive --jobs 0'?")
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800334 sys.exit(1)
335
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800336 def not_exists_or_empty(folder):
Shen Li10224432021-08-12 11:39:31 -0700337 return not os.path.exists(folder) or (os.path.isdir(folder) and len(os.listdir(folder)) == 0)
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800338
339 if bool(os.getenv("USE_SYSTEM_LIBS", False)):
340 return
341 folders = get_submodule_folders()
342 # If none of the submodule folders exists, try to initialize them
343 if all(not_exists_or_empty(folder) for folder in folders):
344 try:
Shen Li10224432021-08-12 11:39:31 -0700345 print(' --- Trying to initialize submodules')
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800346 start = time.time()
Shen Li10224432021-08-12 11:39:31 -0700347 subprocess.check_call(["git", "submodule", "update", "--init", "--recursive"], cwd=cwd)
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800348 end = time.time()
Shen Li10224432021-08-12 11:39:31 -0700349 print(' --- Submodule initialization took {:.2f} sec'.format(end - start))
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800350 except Exception:
Shen Li10224432021-08-12 11:39:31 -0700351 print(' --- Submodule initalization failed')
352 print('Please run:\n\tgit submodule update --init --recursive --jobs 0')
Nikita Shulga7e6a84d2021-03-09 09:09:32 -0800353 sys.exit(1)
354 for folder in folders:
Nikita Shulga6e5d065b2021-08-17 15:28:45 -0700355 check_for_files(folder, ["CMakeLists.txt", "Makefile", "setup.py", "LICENSE", "LICENSE.md", "LICENSE.txt"])
Shen Li10224432021-08-12 11:39:31 -0700356 check_for_files(os.path.join(third_party_path, 'fbgemm', 'third_party',
357 'asmjit'), ['CMakeLists.txt'])
358 check_for_files(os.path.join(third_party_path, 'onnx', 'third_party',
359 'benchmark'), ['CMakeLists.txt'])
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800360
Nikita Shulga272dfc72021-03-01 18:26:24 -0800361
362# all the work we need to do _before_ setup runs
363def build_deps():
Shen Li10224432021-08-12 11:39:31 -0700364 report('-- Building version ' + version)
Nikita Shulga272dfc72021-03-01 18:26:24 -0800365
366 check_submodules()
Shen Li10224432021-08-12 11:39:31 -0700367 check_pydep('yaml', 'pyyaml')
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800368
Shen Li10224432021-08-12 11:39:31 -0700369 build_caffe2(version=version,
370 cmake_python_library=cmake_python_library,
371 build_python=True,
372 rerun_cmake=RERUN_CMAKE,
373 cmake_only=CMAKE_ONLY,
374 cmake=cmake)
Hong Xu081069e2019-10-04 07:48:19 -0700375
Hong Xu9a989ec2019-05-28 17:04:10 -0700376 if CMAKE_ONLY:
Shen Li10224432021-08-12 11:39:31 -0700377 report('Finished running cmake. Run "ccmake build" or '
378 '"cmake-gui build" to adjust build options and '
379 '"python setup.py install" to build.')
Hong Xu9a989ec2019-05-28 17:04:10 -0700380 sys.exit()
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800381
382 # Use copies instead of symbolic files.
383 # Windows has very poor support for them.
Taylor Robie17ea1122020-12-01 19:56:13 -0800384 sym_files = [
Shen Li10224432021-08-12 11:39:31 -0700385 'tools/shared/_utils_internal.py',
386 'torch/utils/benchmark/utils/valgrind_wrapper/callgrind.h',
387 'torch/utils/benchmark/utils/valgrind_wrapper/valgrind.h',
Taylor Robie17ea1122020-12-01 19:56:13 -0800388 ]
389 orig_files = [
Shen Li10224432021-08-12 11:39:31 -0700390 'torch/_utils_internal.py',
391 'third_party/valgrind-headers/callgrind.h',
392 'third_party/valgrind-headers/valgrind.h',
Taylor Robie17ea1122020-12-01 19:56:13 -0800393 ]
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800394 for sym_file, orig_file in zip(sym_files, orig_files):
395 same = False
396 if os.path.exists(sym_file):
397 if filecmp.cmp(sym_file, orig_file):
398 same = True
399 else:
400 os.remove(sym_file)
401 if not same:
402 shutil.copyfile(orig_file, sym_file)
403
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700404################################################################################
405# Building dependent libraries
Adam Paszke690d4702016-05-03 15:11:32 +0200406################################################################################
Adam Paszke842e1b62016-05-05 20:58:13 +0200407
Soumith Chintala6313d5e2019-08-04 17:17:33 -0700408# the list of runtime dependencies required by this built package
Shen Li10224432021-08-12 11:39:31 -0700409install_requires = [
410 'typing_extensions',
Shen Li10224432021-08-12 11:39:31 -0700411]
Soumith Chintala6313d5e2019-08-04 17:17:33 -0700412
Shen Li10224432021-08-12 11:39:31 -0700413missing_pydep = '''
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700414Missing build dependency: Unable to `import {importname}`.
415Please install it via `conda install {module}` or `pip install {module}`
Shen Li10224432021-08-12 11:39:31 -0700416'''.strip()
Sam Gross966fdbd2017-08-23 07:16:06 -0400417
Soumith Chintala5e372c72018-06-06 12:53:58 -0400418
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700419def check_pydep(importname, module):
420 try:
421 importlib.import_module(importname)
422 except ImportError:
423 raise RuntimeError(missing_pydep.format(importname=importname, module=module))
Zachary DeVito0e54c3a982017-11-29 16:10:51 -0500424
Soumith Chintala5e372c72018-06-06 12:53:58 -0400425
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800426class build_ext(setuptools.command.build_ext.build_ext):
Nikita Shulga14194e42020-11-03 12:55:14 -0800427
428 # Copy libiomp5.dylib inside the wheel package on OS X
429 def _embed_libiomp(self):
430 if not IS_DARWIN:
431 return
Shen Li10224432021-08-12 11:39:31 -0700432 lib_dir = os.path.join(self.build_lib, 'torch', 'lib')
433 libtorch_cpu_path = os.path.join(lib_dir, 'libtorch_cpu.dylib')
Nikita Shulga6f602512020-11-04 14:13:10 -0800434 if not os.path.exists(libtorch_cpu_path):
435 return
Nikita Shulga14194e42020-11-03 12:55:14 -0800436 # Parse libtorch_cpu load commands
Shen Li10224432021-08-12 11:39:31 -0700437 otool_cmds = subprocess.check_output(['otool', '-l', libtorch_cpu_path]).decode('utf-8').split('\n')
Nikita Shulga14194e42020-11-03 12:55:14 -0800438 rpaths, libs = [], []
439 for idx, line in enumerate(otool_cmds):
Shen Li10224432021-08-12 11:39:31 -0700440 if line.strip() == 'cmd LC_LOAD_DYLIB':
Nikita Shulga14194e42020-11-03 12:55:14 -0800441 lib_name = otool_cmds[idx + 2].strip()
Shen Li10224432021-08-12 11:39:31 -0700442 assert lib_name.startswith('name ')
443 libs.append(lib_name.split(' ', 1)[1].rsplit('(', 1)[0][:-1])
Nikita Shulga14194e42020-11-03 12:55:14 -0800444
Shen Li10224432021-08-12 11:39:31 -0700445 if line.strip() == 'cmd LC_RPATH':
Nikita Shulga14194e42020-11-03 12:55:14 -0800446 rpath = otool_cmds[idx + 2].strip()
Shen Li10224432021-08-12 11:39:31 -0700447 assert rpath.startswith('path ')
448 rpaths.append(rpath.split(' ', 1)[1].rsplit('(', 1)[0][:-1])
Nikita Shulga14194e42020-11-03 12:55:14 -0800449
Shen Li10224432021-08-12 11:39:31 -0700450 omp_lib_name = 'libiomp5.dylib'
451 if os.path.join('@rpath', omp_lib_name) not in libs:
Nikita Shulga14194e42020-11-03 12:55:14 -0800452 return
453
454 # Copy libiomp5 from rpath locations
455 for rpath in rpaths:
456 source_lib = os.path.join(rpath, omp_lib_name)
457 if not os.path.exists(source_lib):
458 continue
Shen Li10224432021-08-12 11:39:31 -0700459 target_lib = os.path.join(self.build_lib, 'torch', 'lib', omp_lib_name)
Nikita Shulga14194e42020-11-03 12:55:14 -0800460 self.copy_file(source_lib, target_lib)
461 break
462
Adam Paszke207d6ae2016-08-14 20:47:27 -0700463 def run(self):
Hong Xu04086972019-06-17 13:42:45 -0700464 # Report build options. This is run after the build completes so # `CMakeCache.txt` exists and we can get an
465 # accurate report on what is used and what is not.
Hong Xub811b6d2019-06-14 08:10:18 -0700466 cmake_cache_vars = defaultdict(lambda: False, cmake.get_cmake_cache_variables())
Shen Li10224432021-08-12 11:39:31 -0700467 if cmake_cache_vars['USE_NUMPY']:
468 report('-- Building with NumPy bindings')
Adam Paszke08d346d2016-12-15 00:04:28 +0100469 else:
Shen Li10224432021-08-12 11:39:31 -0700470 report('-- NumPy not found')
471 if cmake_cache_vars['USE_CUDNN']:
472 report('-- Detected cuDNN at ' +
473 cmake_cache_vars['CUDNN_LIBRARY'] + ', ' + cmake_cache_vars['CUDNN_INCLUDE_DIR'])
Adam Paszke08d346d2016-12-15 00:04:28 +0100474 else:
Shen Li10224432021-08-12 11:39:31 -0700475 report('-- Not using cuDNN')
476 if cmake_cache_vars['USE_CUDA']:
477 report('-- Detected CUDA at ' + cmake_cache_vars['CUDA_TOOLKIT_ROOT_DIR'])
Adam Paszke08d346d2016-12-15 00:04:28 +0100478 else:
Shen Li10224432021-08-12 11:39:31 -0700479 report('-- Not using CUDA')
480 if cmake_cache_vars['USE_MKLDNN']:
481 report('-- Using MKLDNN')
482 if cmake_cache_vars['USE_MKLDNN_ACL']:
483 report('-- Using Compute Library for the Arm architecture with MKLDNN')
Nathan John Sircombebf00d262021-05-20 07:42:48 -0700484 else:
Shen Li10224432021-08-12 11:39:31 -0700485 report('-- Not using Compute Library for the Arm architecture with MKLDNN')
486 if cmake_cache_vars['USE_MKLDNN_CBLAS']:
487 report('-- Using CBLAS in MKLDNN')
Hui Wu07ef85e2019-07-02 12:22:20 -0700488 else:
Shen Li10224432021-08-12 11:39:31 -0700489 report('-- Not using CBLAS in MKLDNN')
Ma Mingfeif8270c02018-03-30 06:25:07 +0800490 else:
Shen Li10224432021-08-12 11:39:31 -0700491 report('-- Not using MKLDNN')
492 if cmake_cache_vars['USE_NCCL'] and cmake_cache_vars['USE_SYSTEM_NCCL']:
493 report('-- Using system provided NCCL library at {}, {}'.format(cmake_cache_vars['NCCL_LIBRARIES'],
494 cmake_cache_vars['NCCL_INCLUDE_DIRS']))
495 elif cmake_cache_vars['USE_NCCL']:
496 report('-- Building NCCL library')
Sam Grossb9379cf2017-03-16 16:10:17 -0400497 else:
Shen Li10224432021-08-12 11:39:31 -0700498 report('-- Not using NCCL')
499 if cmake_cache_vars['USE_DISTRIBUTED']:
Pieter Noordhuis3556bea2019-09-05 07:08:12 -0700500 if IS_WINDOWS:
Shen Li10224432021-08-12 11:39:31 -0700501 report('-- Building without distributed package')
Teng Li020501b2018-09-04 17:18:29 -0700502 else:
Shen Li10224432021-08-12 11:39:31 -0700503 report('-- Building with distributed package: ')
504 report(' -- USE_TENSORPIPE={}'.format(cmake_cache_vars['USE_TENSORPIPE']))
505 report(' -- USE_GLOO={}'.format(cmake_cache_vars['USE_GLOO']))
506 report(' -- USE_MPI={}'.format(cmake_cache_vars['USE_OPENMPI']))
Adam Paszke714351f2017-06-07 06:36:20 -0400507 else:
Shen Li10224432021-08-12 11:39:31 -0700508 report('-- Building without distributed package')
peterjc123aa911932017-11-09 02:51:35 +0800509
Nikita Shulga2dff0b32020-11-24 10:55:00 -0800510 # Do not use clang to compile extensions if `-fstack-clash-protection` is defined
Nikita Shulgadd7cec62020-03-10 15:29:07 -0700511 # in system CFLAGS
Shen Li10224432021-08-12 11:39:31 -0700512 c_flags = str(os.getenv('CFLAGS', ''))
513 if IS_LINUX and '-fstack-clash-protection' in c_flags and 'clang' in os.environ.get('CC', ''):
514 os.environ['CC'] = str(os.environ['CC'])
Nikita Shulgadd7cec62020-03-10 15:29:07 -0700515
Adam Paszkeb06c0002016-08-16 21:02:46 -0700516 # It's an old-style class in Python 2.7...
517 setuptools.command.build_ext.build_ext.run(self)
518
Nikita Shulga14194e42020-11-03 12:55:14 -0800519 self._embed_libiomp()
520
peterjc12363af8982018-04-03 01:53:25 +0800521 # Copy the essential export library to compile C++ extensions.
522 if IS_WINDOWS:
523 build_temp = self.build_temp
524
Shen Li10224432021-08-12 11:39:31 -0700525 ext_filename = self.get_ext_filename('_C')
526 lib_filename = '.'.join(ext_filename.split('.')[:-1]) + '.lib'
peterjc12363af8982018-04-03 01:53:25 +0800527
528 export_lib = os.path.join(
Shen Li10224432021-08-12 11:39:31 -0700529 build_temp, 'torch', 'csrc', lib_filename).replace('\\', '/')
peterjc12363af8982018-04-03 01:53:25 +0800530
531 build_lib = self.build_lib
532
Shen Li10224432021-08-12 11:39:31 -0700533 target_lib = os.path.join(
534 build_lib, 'torch', 'lib', '_C.lib').replace('\\', '/')
peterjc12363af8982018-04-03 01:53:25 +0800535
Shuichi KITAGUCHIddbfdc92019-04-01 07:24:27 -0700536 # Create "torch/lib" directory if not exists.
537 # (It is not created yet in "develop" mode.)
538 target_dir = os.path.dirname(target_lib)
539 if not os.path.exists(target_dir):
540 os.makedirs(target_dir)
541
peterjc12363af8982018-04-03 01:53:25 +0800542 self.copy_file(export_lib, target_lib)
543
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700544 def build_extensions(self):
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800545 self.create_compile_commands()
Jesse Hellemn99ab0822018-07-09 18:04:25 -0700546 # The caffe2 extensions are created in
andersj8a5ba572019-01-08 15:54:20 -0800547 # tmp_install/lib/pythonM.m/site-packages/caffe2/python/
Jesse Hellemn99ab0822018-07-09 18:04:25 -0700548 # and need to be copied to build/lib.linux.... , which will be a
549 # platform dependent build folder created by the "build" command of
550 # setuptools. Only the contents of this folder are installed in the
551 # "install" command by default.
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700552 # We only make this copy for Caffe2's pybind extensions
553 caffe2_pybind_exts = [
Shen Li10224432021-08-12 11:39:31 -0700554 'caffe2.python.caffe2_pybind11_state',
555 'caffe2.python.caffe2_pybind11_state_gpu',
556 'caffe2.python.caffe2_pybind11_state_hip',
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700557 ]
558 i = 0
559 while i < len(self.extensions):
560 ext = self.extensions[i]
561 if ext.name not in caffe2_pybind_exts:
562 i += 1
563 continue
564 fullname = self.get_ext_fullname(ext.name)
565 filename = self.get_ext_filename(fullname)
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800566 report("\nCopying extension {}".format(ext.name))
Paul Jesse Hellemn8e6f7a12018-06-06 08:31:31 -0700567
Shen Li10224432021-08-12 11:39:31 -0700568 relative_site_packages = sysconfig.get_path('purelib').replace(sysconfig.get_path('data'), '').lstrip(os.path.sep)
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700569 src = os.path.join("torch", relative_site_packages, filename)
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700570 if not os.path.exists(src):
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800571 report("{} does not exist".format(src))
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700572 del self.extensions[i]
573 else:
574 dst = os.path.join(os.path.realpath(self.build_lib), filename)
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800575 report("Copying {} from {} to {}".format(ext.name, src, dst))
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700576 dst_dir = os.path.dirname(dst)
577 if not os.path.exists(dst_dir):
578 os.makedirs(dst_dir)
579 self.copy_file(src, dst)
580 i += 1
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700581 setuptools.command.build_ext.build_ext.build_extensions(self)
582
Shen Li10224432021-08-12 11:39:31 -0700583
Jesse Hellemn99ab0822018-07-09 18:04:25 -0700584 def get_outputs(self):
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700585 outputs = setuptools.command.build_ext.build_ext.get_outputs(self)
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -0700586 outputs.append(os.path.join(self.build_lib, "caffe2"))
Zachary DeVitoe747acb2018-12-09 22:45:18 -0800587 report("setup.py::get_outputs returning {}".format(outputs))
Jesse Hellemn99ab0822018-07-09 18:04:25 -0700588 return outputs
589
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800590 def create_compile_commands(self):
591 def load(filename):
592 with open(filename) as f:
593 return json.load(f)
Shen Li10224432021-08-12 11:39:31 -0700594 ninja_files = glob.glob('build/*compile_commands.json')
595 cmake_files = glob.glob('torch/lib/build/*/compile_commands.json')
596 all_commands = [entry
597 for f in ninja_files + cmake_files
598 for entry in load(f)]
Adam Paszke207d6ae2016-08-14 20:47:27 -0700599
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800600 # cquery does not like c++ compiles that start with gcc.
601 # It forgets to include the c++ header directories.
602 # We can work around this by replacing the gcc calls that python
603 # setup.py generates with g++ calls instead
604 for command in all_commands:
Shen Li10224432021-08-12 11:39:31 -0700605 if command['command'].startswith("gcc "):
606 command['command'] = "g++ " + command['command'][4:]
Adam Paszke207d6ae2016-08-14 20:47:27 -0700607
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800608 new_contents = json.dumps(all_commands, indent=2)
Shen Li10224432021-08-12 11:39:31 -0700609 contents = ''
610 if os.path.exists('compile_commands.json'):
611 with open('compile_commands.json', 'r') as f:
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800612 contents = f.read()
613 if contents != new_contents:
Shen Li10224432021-08-12 11:39:31 -0700614 with open('compile_commands.json', 'w') as f:
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800615 f.write(new_contents)
Soumith Chintala4e8d9a42018-09-11 08:51:19 -0700616
Shen Li10224432021-08-12 11:39:31 -0700617class concat_license_files():
mattip9cbefad2021-02-08 08:23:56 -0800618 """Merge LICENSE and LICENSES_BUNDLED.txt as a context manager
619
620 LICENSE is the main PyTorch license, LICENSES_BUNDLED.txt is auto-generated
621 from all the licenses found in ./third_party/. We concatenate them so there
622 is a single license file in the sdist and wheels with all of the necessary
623 licensing info.
624 """
625 def __init__(self):
Shen Li10224432021-08-12 11:39:31 -0700626 self.f1 = 'LICENSE'
627 self.f2 = 'third_party/LICENSES_BUNDLED.txt'
mattip9cbefad2021-02-08 08:23:56 -0800628
629 def __enter__(self):
630 """Concatenate files"""
Shen Li10224432021-08-12 11:39:31 -0700631 with open(self.f1, 'r') as f1:
mattip9cbefad2021-02-08 08:23:56 -0800632 self.bsd_text = f1.read()
633
Shen Li10224432021-08-12 11:39:31 -0700634 with open(self.f1, 'a') as f1:
635 with open(self.f2, 'r') as f2:
mattip9cbefad2021-02-08 08:23:56 -0800636 self.bundled_text = f2.read()
Shen Li10224432021-08-12 11:39:31 -0700637 f1.write('\n\n')
mattip9cbefad2021-02-08 08:23:56 -0800638 f1.write(self.bundled_text)
639
640 def __exit__(self, exception_type, exception_value, traceback):
641 """Restore content of f1"""
Shen Li10224432021-08-12 11:39:31 -0700642 with open(self.f1, 'w') as f:
mattip9cbefad2021-02-08 08:23:56 -0800643 f.write(self.bsd_text)
644
645
646try:
647 from wheel.bdist_wheel import bdist_wheel
648except ImportError:
649 # This is useful when wheel is not installed and bdist_wheel is not
650 # specified on the command line. If it _is_ specified, parsing the command
651 # line will fail before wheel_concatenate is needed
652 wheel_concatenate = None
653else:
654 # Need to create the proper LICENSE.txt for the wheel
655 class wheel_concatenate(bdist_wheel):
Shen Li10224432021-08-12 11:39:31 -0700656 """ check submodules on sdist to prevent incomplete tarballs """
mattip9cbefad2021-02-08 08:23:56 -0800657 def run(self):
658 with concat_license_files():
659 super().run()
660
Soumith Chintala4e8d9a42018-09-11 08:51:19 -0700661
Adam Paszkeb06c0002016-08-16 21:02:46 -0700662class install(setuptools.command.install.install):
663 def run(self):
Nikita Shulga272dfc72021-03-01 18:26:24 -0800664 super().run()
Adam Paszkeb06c0002016-08-16 21:02:46 -0700665
666
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700667class clean(setuptools.Command):
668 user_options = []
669
670 def initialize_options(self):
671 pass
672
673 def finalize_options(self):
674 pass
675
Adam Paszke207d6ae2016-08-14 20:47:27 -0700676 def run(self):
Soumith Chintala140c65e2016-10-21 23:16:39 -0400677 import glob
Shuichi KITAGUCHIdf23bdc2018-08-05 15:47:02 -0700678 import re
Shen Li10224432021-08-12 11:39:31 -0700679 with open('.gitignore', 'r') as f:
Adam Paszke207d6ae2016-08-14 20:47:27 -0700680 ignores = f.read()
Shen Li10224432021-08-12 11:39:31 -0700681 pat = re.compile(r'^#( BEGIN NOT-CLEAN-FILES )?')
682 for wildcard in filter(None, ignores.split('\n')):
Shuichi KITAGUCHIdf23bdc2018-08-05 15:47:02 -0700683 match = pat.match(wildcard)
684 if match:
685 if match.group(1):
686 # Marker is found and stop reading .gitignore.
687 break
688 # Ignore lines which begin with '#'.
689 else:
690 for filename in glob.glob(wildcard):
691 try:
692 os.remove(filename)
693 except OSError:
694 shutil.rmtree(filename, ignore_errors=True)
Sam Grossf2d7e942016-10-26 09:51:52 -0700695
Nikita Shulga272dfc72021-03-01 18:26:24 -0800696
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700697class sdist(setuptools.command.sdist.sdist):
Nikita Shulga272dfc72021-03-01 18:26:24 -0800698 def run(self):
699 with concat_license_files():
700 super().run()
701
Adam Paszkeb06c0002016-08-16 21:02:46 -0700702
Hong Xub811b6d2019-06-14 08:10:18 -0700703def configure_extension_build():
704 r"""Configures extension build options according to system environment and user's choice.
Adam Paszke207d6ae2016-08-14 20:47:27 -0700705
Hong Xub811b6d2019-06-14 08:10:18 -0700706 Returns:
707 The input to parameters ext_modules, cmdclass, packages, and entry_points as required in setuptools.setup.
708 """
Adam Paszkee9f9fd32016-08-10 09:19:13 -0700709
Hong Xub811b6d2019-06-14 08:10:18 -0700710 try:
711 cmake_cache_vars = defaultdict(lambda: False, cmake.get_cmake_cache_variables())
712 except FileNotFoundError:
713 # CMakeCache.txt does not exist. Probably running "python setup.py clean" over a clean directory.
714 cmake_cache_vars = defaultdict(lambda: False)
peterjc123aa911932017-11-09 02:51:35 +0800715
Hong Xub811b6d2019-06-14 08:10:18 -0700716 ################################################################################
717 # Configure compile flags
718 ################################################################################
Adam Paszkee9f9fd32016-08-10 09:19:13 -0700719
Hong Xub811b6d2019-06-14 08:10:18 -0700720 library_dirs = []
Eli Uriegas275f5c82020-03-17 13:24:14 -0700721 extra_install_requires = []
Adam Paszkee9f9fd32016-08-10 09:19:13 -0700722
peterjc123aa911932017-11-09 02:51:35 +0800723 if IS_WINDOWS:
Hong Xub811b6d2019-06-14 08:10:18 -0700724 # /NODEFAULTLIB makes sure we only link to DLL runtime
725 # and matches the flags set for protobuf and ONNX
Shen Li10224432021-08-12 11:39:31 -0700726 extra_link_args = ['/NODEFAULTLIB:LIBCMT.LIB']
Hong Xub811b6d2019-06-14 08:10:18 -0700727 # /MD links against DLL runtime
728 # and matches the flags set for protobuf and ONNX
peterc5d6f59a2020-04-28 08:16:40 -0700729 # /EHsc is about standard C++ exception handling
Hong Xub811b6d2019-06-14 08:10:18 -0700730 # /DNOMINMAX removes builtin min/max functions
731 # /wdXXXX disables warning no. XXXX
Shen Li10224432021-08-12 11:39:31 -0700732 extra_compile_args = ['/MD', '/EHsc', '/DNOMINMAX',
733 '/wd4267', '/wd4251', '/wd4522', '/wd4522', '/wd4838',
734 '/wd4305', '/wd4244', '/wd4190', '/wd4101', '/wd4996',
735 '/wd4275']
peterjc123aa911932017-11-09 02:51:35 +0800736 else:
Hong Xub811b6d2019-06-14 08:10:18 -0700737 extra_link_args = []
738 extra_compile_args = [
Shen Li10224432021-08-12 11:39:31 -0700739 '-Wall',
740 '-Wextra',
741 '-Wno-strict-overflow',
742 '-Wno-unused-parameter',
743 '-Wno-missing-field-initializers',
744 '-Wno-write-strings',
745 '-Wno-unknown-pragmas',
Hong Xub811b6d2019-06-14 08:10:18 -0700746 # This is required for Python 2 declarations that are deprecated in 3.
Shen Li10224432021-08-12 11:39:31 -0700747 '-Wno-deprecated-declarations',
Hong Xub811b6d2019-06-14 08:10:18 -0700748 # Python 2.6 requires -fno-strict-aliasing, see
749 # http://legacy.python.org/dev/peps/pep-3123/
750 # We also depend on it in our code (even Python 3).
Shen Li10224432021-08-12 11:39:31 -0700751 '-fno-strict-aliasing',
Hong Xub811b6d2019-06-14 08:10:18 -0700752 # Clang has an unfixed bug leading to spurious missing
753 # braces warnings, see
754 # https://bugs.llvm.org/show_bug.cgi?id=21629
Shen Li10224432021-08-12 11:39:31 -0700755 '-Wno-missing-braces',
Hong Xub811b6d2019-06-14 08:10:18 -0700756 ]
Johannes M Dietericha4c59a92018-08-23 15:20:02 -0700757
Hong Xub811b6d2019-06-14 08:10:18 -0700758 library_dirs.append(lib_path)
Adam Paszkee9f9fd32016-08-10 09:19:13 -0700759
Hong Xub811b6d2019-06-14 08:10:18 -0700760 main_compile_args = []
Shen Li10224432021-08-12 11:39:31 -0700761 main_libraries = ['torch_python']
Hong Xub811b6d2019-06-14 08:10:18 -0700762 main_link_args = []
Nikita Shulgaa864dbb2020-06-02 13:07:55 -0700763 main_sources = ["torch/csrc/stub.c"]
Hong Xub811b6d2019-06-14 08:10:18 -0700764
Shen Li10224432021-08-12 11:39:31 -0700765 if cmake_cache_vars['USE_CUDA']:
766 library_dirs.append(
767 os.path.dirname(cmake_cache_vars['CUDA_CUDA_LIB']))
Hong Xub811b6d2019-06-14 08:10:18 -0700768
Hong Xufd1d06e2019-07-24 08:02:43 -0700769 if build_type.is_debug():
Hong Xub811b6d2019-06-14 08:10:18 -0700770 if IS_WINDOWS:
Shen Li10224432021-08-12 11:39:31 -0700771 extra_compile_args.append('/Z7')
772 extra_link_args.append('/DEBUG:FULL')
Hong Xub811b6d2019-06-14 08:10:18 -0700773 else:
Shen Li10224432021-08-12 11:39:31 -0700774 extra_compile_args += ['-O0', '-g']
775 extra_link_args += ['-O0', '-g']
Hong Xub811b6d2019-06-14 08:10:18 -0700776
Hong Xufd1d06e2019-07-24 08:02:43 -0700777 if build_type.is_rel_with_deb_info():
Hong Xub811b6d2019-06-14 08:10:18 -0700778 if IS_WINDOWS:
Shen Li10224432021-08-12 11:39:31 -0700779 extra_compile_args.append('/Z7')
780 extra_link_args.append('/DEBUG:FULL')
Hong Xub811b6d2019-06-14 08:10:18 -0700781 else:
Shen Li10224432021-08-12 11:39:31 -0700782 extra_compile_args += ['-g']
783 extra_link_args += ['-g']
Zachary DeVito788d2e82018-11-21 06:36:26 -0800784
Nikita Shulgae8e570e2021-03-16 00:21:55 -0700785 # Cross-compile for M1
786 if IS_DARWIN:
Shen Li10224432021-08-12 11:39:31 -0700787 macos_target_arch = os.getenv('CMAKE_OSX_ARCHITECTURES', '')
788 if macos_target_arch in ['arm64', 'x86_64']:
789 macos_sysroot_path = os.getenv('CMAKE_OSX_SYSROOT')
Nikita Shulgae8e570e2021-03-16 00:21:55 -0700790 if macos_sysroot_path is None:
Shen Li10224432021-08-12 11:39:31 -0700791 macos_sysroot_path = subprocess.check_output([
792 'xcrun', '--show-sdk-path', '--sdk', 'macosx'
793 ]).decode('utf-8').strip()
794 extra_compile_args += ['-arch', macos_target_arch, '-isysroot', macos_sysroot_path]
795 extra_link_args += ['-arch', macos_target_arch]
796
Adam Paszke8d933cb2016-08-22 22:45:35 -0400797
petera08e8dd2020-11-09 11:36:56 -0800798 def make_relative_rpath_args(path):
Hong Xub811b6d2019-06-14 08:10:18 -0700799 if IS_DARWIN:
Shen Li10224432021-08-12 11:39:31 -0700800 return ['-Wl,-rpath,@loader_path/' + path]
Hong Xub811b6d2019-06-14 08:10:18 -0700801 elif IS_WINDOWS:
petera08e8dd2020-11-09 11:36:56 -0800802 return []
Hong Xub811b6d2019-06-14 08:10:18 -0700803 else:
Shen Li10224432021-08-12 11:39:31 -0700804 return ['-Wl,-rpath,$ORIGIN/' + path]
Adam Paszke8d933cb2016-08-22 22:45:35 -0400805
Hong Xub811b6d2019-06-14 08:10:18 -0700806 ################################################################################
807 # Declare extensions and package
808 ################################################################################
Adam Paszkee9f9fd32016-08-10 09:19:13 -0700809
Hong Xub811b6d2019-06-14 08:10:18 -0700810 extensions = []
Shen Li10224432021-08-12 11:39:31 -0700811 packages = find_packages(exclude=('tools', 'tools.*'))
812 C = Extension("torch._C",
813 libraries=main_libraries,
814 sources=main_sources,
815 language='c',
816 extra_compile_args=main_compile_args + extra_compile_args,
817 include_dirs=[],
818 library_dirs=library_dirs,
819 extra_link_args=extra_link_args + main_link_args + make_relative_rpath_args('lib'))
Hong Xub811b6d2019-06-14 08:10:18 -0700820 extensions.append(C)
Adam Paszkee9f9fd32016-08-10 09:19:13 -0700821
Hong Xub811b6d2019-06-14 08:10:18 -0700822 if not IS_WINDOWS:
Shen Li10224432021-08-12 11:39:31 -0700823 DL = Extension("torch._dl",
824 sources=["torch/csrc/dl.c"],
825 language='c')
Hong Xub811b6d2019-06-14 08:10:18 -0700826 extensions.append(DL)
Soumith Chintala1cf87e82016-09-25 18:56:41 -0400827
Hong Xub811b6d2019-06-14 08:10:18 -0700828 # These extensions are built by cmake and copied manually in build_extensions()
Nikita Shulgaa864dbb2020-06-02 13:07:55 -0700829 # inside the build_ext implementation
Nikita Shulga77becca2021-10-21 20:31:01 -0700830 if cmake_cache_vars['BUILD_CAFFE2']:
Hong Xub811b6d2019-06-14 08:10:18 -0700831 extensions.append(
Shen Li10224432021-08-12 11:39:31 -0700832 Extension(
Nikita Shulga77becca2021-10-21 20:31:01 -0700833 name=str('caffe2.python.caffe2_pybind11_state'),
Shen Li10224432021-08-12 11:39:31 -0700834 sources=[]),
Hong Xub811b6d2019-06-14 08:10:18 -0700835 )
Nikita Shulga77becca2021-10-21 20:31:01 -0700836 if cmake_cache_vars['USE_CUDA']:
837 extensions.append(
838 Extension(
839 name=str('caffe2.python.caffe2_pybind11_state_gpu'),
840 sources=[]),
841 )
842 if cmake_cache_vars['USE_ROCM']:
843 extensions.append(
844 Extension(
845 name=str('caffe2.python.caffe2_pybind11_state_hip'),
846 sources=[]),
847 )
Adam Paszke1bdc2812017-02-15 11:48:08 -0800848
Hong Xub811b6d2019-06-14 08:10:18 -0700849 cmdclass = {
Shen Li10224432021-08-12 11:39:31 -0700850 'bdist_wheel': wheel_concatenate,
851 'build_ext': build_ext,
852 'clean': clean,
853 'install': install,
854 'sdist': sdist,
Hong Xub811b6d2019-06-14 08:10:18 -0700855 }
soumithe4812b32017-01-17 14:13:44 -0800856
Hong Xub811b6d2019-06-14 08:10:18 -0700857 entry_points = {
Shen Li10224432021-08-12 11:39:31 -0700858 'console_scripts': [
859 'convert-caffe2-to-onnx = caffe2.python.onnx.bin.conversion:caffe2_to_onnx',
860 'convert-onnx-to-caffe2 = caffe2.python.onnx.bin.conversion:onnx_to_caffe2',
Can Balioglu65e61942021-08-26 20:16:10 -0700861 'torchrun = torch.distributed.run:main',
Hong Xub811b6d2019-06-14 08:10:18 -0700862 ]
863 }
864
Eli Uriegas275f5c82020-03-17 13:24:14 -0700865 return extensions, cmdclass, packages, entry_points, extra_install_requires
Jesse Hellemndef37152018-08-10 11:55:03 -0700866
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800867# post run, warnings, printed at the end to make them more visible
868build_update_message = """
869 It is no longer necessary to use the 'build' or 'rebuild' targets
870
871 To install:
872 $ python setup.py install
873 To develop locally:
874 $ python setup.py develop
Hong Xu646a7f92019-06-11 07:00:51 -0700875 To force cmake to re-generate native build files (off by default):
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800876 $ python setup.py develop --cmake
877"""
878
879
880def print_box(msg):
Shen Li10224432021-08-12 11:39:31 -0700881 lines = msg.split('\n')
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800882 size = max(len(l) + 1 for l in lines)
Shen Li10224432021-08-12 11:39:31 -0700883 print('-' * (size + 2))
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800884 for l in lines:
Shen Li10224432021-08-12 11:39:31 -0700885 print('|{}{}|'.format(l, ' ' * (size - len(l))))
886 print('-' * (size + 2))
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800887
Shen Li10224432021-08-12 11:39:31 -0700888if __name__ == '__main__':
Simeon Monovbad44422019-02-12 00:12:03 -0800889 # Parse the command line and check the arguments
890 # before we proceed with building deps and setup
891 dist = Distribution()
Simeon Monovbad44422019-02-12 00:12:03 -0800892 try:
davidriazati@fb.com4b96fc02021-04-29 12:09:02 -0700893 dist.parse_command_line()
894 except setuptools.distutils.errors.DistutilsArgError as e:
895 print(e)
896 sys.exit(1)
Simeon Monovbad44422019-02-12 00:12:03 -0800897
Zachary DeVito0cd1ab82019-01-21 17:24:32 -0800898 if RUN_BUILD_DEPS:
899 build_deps()
Hong Xub811b6d2019-06-14 08:10:18 -0700900
Shen Li10224432021-08-12 11:39:31 -0700901 extensions, cmdclass, packages, entry_points, extra_install_requires = configure_extension_build()
Eli Uriegas275f5c82020-03-17 13:24:14 -0700902
903 install_requires += extra_install_requires
Hong Xub811b6d2019-06-14 08:10:18 -0700904
Eli Uriegasb7b74332020-06-08 16:11:11 -0700905 # Read in README.md for our long_description
906 with open(os.path.join(cwd, "README.md"), encoding="utf-8") as f:
907 long_description = f.read()
908
Nikita Shulga14a25012021-03-26 12:39:40 -0700909 version_range_max = max(sys.version_info[1], 9) + 1
Peter Goldsborough1262fba2018-01-22 16:49:11 -0800910 setup(
Jesse Hellemndef37152018-08-10 11:55:03 -0700911 name=package_name,
Peter Goldsborough1262fba2018-01-22 16:49:11 -0800912 version=version,
Shen Li10224432021-08-12 11:39:31 -0700913 description=("Tensors and Dynamic neural networks in "
914 "Python with strong GPU acceleration"),
Eli Uriegasb7b74332020-06-08 16:11:11 -0700915 long_description=long_description,
916 long_description_content_type="text/markdown",
Peter Goldsborough1262fba2018-01-22 16:49:11 -0800917 ext_modules=extensions,
918 cmdclass=cmdclass,
919 packages=packages,
Jesse Hellemndef37152018-08-10 11:55:03 -0700920 entry_points=entry_points,
Soumith Chintala6313d5e2019-08-04 17:17:33 -0700921 install_requires=install_requires,
Peter Goldsborough1262fba2018-01-22 16:49:11 -0800922 package_data={
Shen Li10224432021-08-12 11:39:31 -0700923 'torch': [
924 'py.typed',
925 'bin/*',
926 'test/*',
927 '_C/*.pyi',
928 'cuda/*.pyi',
929 'optim/*.pyi',
930 'autograd/*.pyi',
931 'utils/data/*.pyi',
932 'nn/*.pyi',
933 'nn/modules/*.pyi',
934 'nn/parallel/*.pyi',
935 'lib/*.so*',
936 'lib/*.dylib*',
937 'lib/*.dll',
938 'lib/*.lib',
939 'lib/*.pdb',
940 'lib/torch_shm_manager',
941 'lib/*.h',
942 'include/ATen/*.h',
943 'include/ATen/cpu/*.h',
944 'include/ATen/cpu/vec/vec256/*.h',
945 'include/ATen/cpu/vec/vec512/*.h',
946 'include/ATen/cpu/vec/*.h',
947 'include/ATen/core/*.h',
948 'include/ATen/cuda/*.cuh',
949 'include/ATen/cuda/*.h',
950 'include/ATen/cuda/detail/*.cuh',
951 'include/ATen/cuda/detail/*.h',
952 'include/ATen/cudnn/*.h',
Peter Bell4829dce2021-12-14 06:38:39 -0800953 'include/ATen/ops/*.h',
Shen Li10224432021-08-12 11:39:31 -0700954 'include/ATen/hip/*.cuh',
955 'include/ATen/hip/*.h',
956 'include/ATen/hip/detail/*.cuh',
957 'include/ATen/hip/detail/*.h',
958 'include/ATen/hip/impl/*.h',
959 'include/ATen/detail/*.h',
960 'include/ATen/native/*.h',
961 'include/ATen/native/cpu/*.h',
962 'include/ATen/native/cuda/*.h',
963 'include/ATen/native/cuda/*.cuh',
964 'include/ATen/native/hip/*.h',
965 'include/ATen/native/hip/*.cuh',
966 'include/ATen/native/quantized/*.h',
967 'include/ATen/native/quantized/cpu/*.h',
968 'include/ATen/quantized/*.h',
969 'include/caffe2/utils/*.h',
970 'include/caffe2/utils/**/*.h',
971 'include/c10/*.h',
972 'include/c10/macros/*.h',
973 'include/c10/core/*.h',
974 'include/ATen/core/boxing/*.h',
975 'include/ATen/core/boxing/impl/*.h',
976 'include/ATen/core/dispatch/*.h',
977 'include/ATen/core/op_registration/*.h',
978 'include/c10/core/impl/*.h',
979 'include/c10/util/*.h',
980 'include/c10/cuda/*.h',
981 'include/c10/cuda/impl/*.h',
982 'include/c10/hip/*.h',
983 'include/c10/hip/impl/*.h',
984 'include/c10d/*.hpp',
985 'include/caffe2/**/*.h',
986 'include/torch/*.h',
987 'include/torch/csrc/*.h',
988 'include/torch/csrc/api/include/torch/*.h',
989 'include/torch/csrc/api/include/torch/data/*.h',
990 'include/torch/csrc/api/include/torch/data/dataloader/*.h',
991 'include/torch/csrc/api/include/torch/data/datasets/*.h',
992 'include/torch/csrc/api/include/torch/data/detail/*.h',
993 'include/torch/csrc/api/include/torch/data/samplers/*.h',
994 'include/torch/csrc/api/include/torch/data/transforms/*.h',
995 'include/torch/csrc/api/include/torch/detail/*.h',
996 'include/torch/csrc/api/include/torch/detail/ordered_dict.h',
997 'include/torch/csrc/api/include/torch/nn/*.h',
998 'include/torch/csrc/api/include/torch/nn/functional/*.h',
999 'include/torch/csrc/api/include/torch/nn/options/*.h',
1000 'include/torch/csrc/api/include/torch/nn/modules/*.h',
1001 'include/torch/csrc/api/include/torch/nn/modules/container/*.h',
1002 'include/torch/csrc/api/include/torch/nn/parallel/*.h',
1003 'include/torch/csrc/api/include/torch/nn/utils/*.h',
1004 'include/torch/csrc/api/include/torch/optim/*.h',
1005 'include/torch/csrc/api/include/torch/optim/schedulers/*.h',
1006 'include/torch/csrc/api/include/torch/serialize/*.h',
1007 'include/torch/csrc/autograd/*.h',
1008 'include/torch/csrc/autograd/functions/*.h',
1009 'include/torch/csrc/autograd/generated/*.h',
1010 'include/torch/csrc/autograd/utils/*.h',
1011 'include/torch/csrc/cuda/*.h',
Michael Suoad182472021-12-01 21:53:29 -08001012 'include/torch/csrc/deploy/*.h',
1013 'include/torch/csrc/deploy/interpreter/interpreter_impl.h',
Can Balioglu6e640a02021-11-16 20:47:57 -08001014 'include/torch/csrc/distributed/c10d/exception.h',
Shen Li10224432021-08-12 11:39:31 -07001015 'include/torch/csrc/jit/*.h',
1016 'include/torch/csrc/jit/backends/*.h',
1017 'include/torch/csrc/jit/generated/*.h',
1018 'include/torch/csrc/jit/passes/*.h',
1019 'include/torch/csrc/jit/passes/quantization/*.h',
1020 'include/torch/csrc/jit/passes/utils/*.h',
1021 'include/torch/csrc/jit/runtime/*.h',
1022 'include/torch/csrc/jit/ir/*.h',
1023 'include/torch/csrc/jit/frontend/*.h',
1024 'include/torch/csrc/jit/api/*.h',
1025 'include/torch/csrc/jit/serialization/*.h',
1026 'include/torch/csrc/jit/python/*.h',
1027 'include/torch/csrc/jit/testing/*.h',
1028 'include/torch/csrc/jit/tensorexpr/*.h',
1029 'include/torch/csrc/jit/tensorexpr/operators/*.h',
1030 'include/torch/csrc/onnx/*.h',
Taylor Robieebc66bf2021-12-16 10:32:13 -08001031 'include/torch/csrc/profiler/*.h',
Shen Li10224432021-08-12 11:39:31 -07001032 'include/torch/csrc/utils/*.h',
1033 'include/torch/csrc/tensor/*.h',
Eli Uriegasf3983202021-11-29 08:26:00 -08001034 'include/torch/csrc/lazy/core/*.h',
Shen Li10224432021-08-12 11:39:31 -07001035 'include/pybind11/*.h',
1036 'include/pybind11/detail/*.h',
1037 'include/TH/*.h*',
1038 'include/TH/generic/*.h*',
1039 'include/THC/*.cuh',
1040 'include/THC/*.h*',
1041 'include/THC/generic/*.h',
Shen Li10224432021-08-12 11:39:31 -07001042 'include/THH/*.cuh',
1043 'include/THH/*.h*',
1044 'include/THH/generic/*.h',
1045 'share/cmake/ATen/*.cmake',
1046 'share/cmake/Caffe2/*.cmake',
1047 'share/cmake/Caffe2/public/*.cmake',
1048 'share/cmake/Caffe2/Modules_CUDA_fix/*.cmake',
1049 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/*.cmake',
1050 'share/cmake/Caffe2/Modules_CUDA_fix/upstream/FindCUDA/*.cmake',
1051 'share/cmake/Gloo/*.cmake',
1052 'share/cmake/Tensorpipe/*.cmake',
1053 'share/cmake/Torch/*.cmake',
1054 'utils/benchmark/utils/*.cpp',
1055 'utils/benchmark/utils/valgrind_wrapper/*.cpp',
1056 'utils/benchmark/utils/valgrind_wrapper/*.h',
1057 'utils/model_dump/skeleton.html',
1058 'utils/model_dump/code.js',
1059 'utils/model_dump/*.mjs',
Jesse Hellemnc0efe6f2018-09-05 16:45:48 -07001060 ],
Shen Li10224432021-08-12 11:39:31 -07001061 'caffe2': [
1062 'python/serialized_test/data/operator_test/*.zip',
Pritam Damaniaf050b162020-01-22 21:05:28 -08001063 ],
Jesse Hellemndef37152018-08-10 11:55:03 -07001064 },
Shen Li10224432021-08-12 11:39:31 -07001065 url='https://pytorch.org/',
1066 download_url='https://github.com/pytorch/pytorch/tags',
1067 author='PyTorch Team',
1068 author_email='packages@pytorch.org',
1069 python_requires='>={}'.format(python_min_version_str),
Soumith Chintaladded7942019-08-01 11:54:40 -07001070 # PyPI package information.
1071 classifiers=[
Shen Li10224432021-08-12 11:39:31 -07001072 'Development Status :: 5 - Production/Stable',
1073 'Intended Audience :: Developers',
1074 'Intended Audience :: Education',
1075 'Intended Audience :: Science/Research',
1076 'License :: OSI Approved :: BSD License',
1077 'Topic :: Scientific/Engineering',
1078 'Topic :: Scientific/Engineering :: Mathematics',
1079 'Topic :: Scientific/Engineering :: Artificial Intelligence',
1080 'Topic :: Software Development',
1081 'Topic :: Software Development :: Libraries',
1082 'Topic :: Software Development :: Libraries :: Python Modules',
1083 'Programming Language :: C++',
1084 'Programming Language :: Python :: 3',
1085 ] + ['Programming Language :: Python :: 3.{}'.format(i) for i in range(python_min_version[1], version_range_max)],
1086 license='BSD-3',
1087 keywords='pytorch machine learning',
Jesse Hellemndef37152018-08-10 11:55:03 -07001088 )
Zachary DeVito0cd1ab82019-01-21 17:24:32 -08001089 if EMIT_BUILD_WARNING:
1090 print_box(build_update_message)