intel-extension-for-pytorch
/
setup.py
1240 строк · 40.2 Кб
1# This Python file uses the following encoding: utf-8
2# !/usr/bin/env python
3
4# Welcome to the Intel Extension for PyTorch setup.py.
5#
6# Environment variables you are probably interested in:
7#
8# DEBUG
9# build with -O0 and -g (debug symbols)
10#
11# RELEASE
12# build with optimization level -O2
13#
14# REL_WITH_DEB_INFO
15# build with optimization level -O2 and -g (debug symbols)
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
20# also applies to C++ files (unless CXXFLAGS is set), in contrast to the
21# default behavior of autogoo and cmake build systems.)
22#
23# CC
24# the C/C++ compiler to use
25#
26# MKLROOT
27# specify MKL library path.
28# ONLY NEEDED if you have a specific MKL version you want to link against.
29# Make sure this directory contains include and lib directories.
30# By default, the MKL library installed with pip/conda is used.
31#
32# Environment variables we respect (these environment variables are
33# conventional and are often understood/set by other software.)
34#
35# TORCH_VERSION
36# specify the PyTorch version to depend on
37#
38# IPEX_VERSION
39# specify the extension version literal
40#
41# MAX_JOBS
42# process for parallel compile, must be a Integer
43#
44# VERBOSE
45# more output when compile
46#
47# IPEX_VERSIONED_BUILD
48# build wheel files versioned with a git commit number
49#
50
51##############################################################
52# XPU Build options:
53# USE_ONEMKL - to use oneMKL in operators
54# USE_CHANNELS_LAST_1D - to use channels last 1d feature
55# USE_PERSIST_STREAM - to use persistent oneDNN stream
56# USE_PRIMITIVE_CACHE - to Cache oneDNN primitives by framework
57# USE_QUEUE_BARRIER - to use queue submit_barrier API
58# USE_SCRATCHPAD_MODE - to trun on oneDNN scratchpad user mode
59# USE_MULTI_CONTEXT - to create DPC++ runtime context per device
60# USE_AOT_DEVLIST - to set device list for AOT build option, for example, bdw,tgl,ats,..."
61# USE_SYCL_ASSERT - to enable assert in sycl kernel
62# USE_ITT_ANNOTATION - to enable ITT annotation in sycl kernel
63# BUILD_STATIC_ONEMKL - to link static oneMKL libraries
64# BUILD_STATS - to count statistics for each component during build process
65# BUILD_BY_PER_KERNEL - to build by DPC++ per_kernel option (exclusive with USE_AOT_DEVLIST)
66# BUILD_STRIPPED_BIN - to strip all symbols after build
67# BUILD_SEPARATE_OPS - to build each operator in separate library
68# BUILD_SIMPLE_TRACE - to build simple trace for each registered operator
69# BUILD_OPT_LEVEL - to add build option -Ox, accept values: 0/1
70# BUILD_NO_CLANGFORMAT - to build without force clang-format
71# BUILD_INTERNAL_DEBUG - to build internal debug code path
72#
73##############################################################
74
75from __future__ import print_function76from distutils.command.build_py import build_py77from distutils.command.install import install78from distutils.version import LooseVersion79from functools import lru_cache80from subprocess import check_call, check_output81from setuptools.command.build_clib import build_clib82from setuptools.command.egg_info import egg_info83from setuptools import setup, distutils84from pathlib import Path85from typing import Any, Optional86
87import sysconfig88import distutils.ccompiler89import distutils.command.clean90import os91import glob92import platform93import shutil94import subprocess95import sys96import errno97
98
99# FIXME: always set BUILD_WITH_XPU = ON in XPU repo
100os.environ["BUILD_WITH_XPU"] = "OFF"101
102
103# Define env values
104ON_ENV_VAL = ["ON", "YES", "1", "Y"]105OFF_ENV_VAL = ["OFF", "NO", "0", "N"]106FULL_ENV_VAL = ON_ENV_VAL + OFF_ENV_VAL107
108
109# initialize variables for compilation
110IS_LINUX = platform.system() == "Linux"111IS_DARWIN = platform.system() == "Darwin"112IS_WINDOWS = platform.system() == "Windows"113
114
115@lru_cache(maxsize=128)116def _get_build_target():117build_target = ""118if len(sys.argv) > 1:119if sys.argv[1] in ["build_clib", "bdist_cppsdk"]:120build_target = "cppsdk"121elif sys.argv[1] in ["clean"]:122build_target = "clean"123elif sys.argv[1] in ["develop"]:124build_target = "develop"125else:126build_target = "python"127return build_target128
129
130torch_install_prefix = None131if _get_build_target() == "cppsdk":132torch_install_prefix = os.environ.get("LIBTORCH_PATH", None)133if torch_install_prefix is None or not os.path.exists(torch_install_prefix):134raise RuntimeError("Can not find libtorch from env LIBTORCH_PATH!")135torch_install_prefix = os.path.abspath(torch_install_prefix)136elif _get_build_target() in ["develop", "python"]:137try:138import torch139from torch.utils.cpp_extension import BuildExtension, CppExtension140except ImportError as e:141raise RuntimeError("Fail to import torch!")142
143
144def _check_env_flag(name, default=""):145return os.getenv(name, default).upper() in ON_ENV_VAL146
147
148def get_build_type():149return (150"RelWithDebInfo"151if _check_env_flag("REL_WITH_DEB_INFO")152else "Debug"153if _check_env_flag("DEBUG")154else "Release"155)156
157
158def create_if_not_exist(path_dir):159if not os.path.exists(path_dir):160try:161Path(path_dir).mkdir(parents=True, exist_ok=True)162except OSError as exc: # Guard against race condition163if exc.errno != errno.EEXIST:164raise RuntimeError("Fail to create path {}".format(path_dir))165
166
167def get_version_num():168versions = {}169version_file = "version.txt"170version_lines = open(version_file, "r").readlines()171for line in version_lines:172key, value = line.strip().split(" ")173versions[key] = value174for v in ("VERSION_MAJOR", "VERSION_MINOR", "VERSION_PATCH"):175if v not in versions:176print("ERROR:", v, "is not found in", version_file)177sys.exit(1)178version = (179versions["VERSION_MAJOR"]180+ "."181+ versions["VERSION_MINOR"]182+ "."183+ versions["VERSION_PATCH"]184)185return version186
187
188PACKAGE_NAME = "intel_extension_for_pytorch"189PYTHON_VERSION = sys.version_info190
191
192def get_pytorch_install_dir():193if _get_build_target() == "clean":194return None195if _get_build_target() == "cppsdk":196return torch_install_prefix197else:198return os.path.dirname(os.path.abspath(torch.__file__))199
200
201pytorch_install_dir = get_pytorch_install_dir()202
203
204def _build_installation_dependency():205install_requires = []206install_requires.append("psutil")207install_requires.append("numpy")208install_requires.append("packaging")209return install_requires210
211
212def which(thefile: str) -> Optional[str]:213path = os.environ.get("PATH", os.defpath).split(os.pathsep)214for d in path:215fname = os.path.join(d, thefile)216fnames = [fname]217if sys.platform == "win32":218exts = os.environ.get("PATHEXT", "").split(os.pathsep)219fnames += [fname + ext for ext in exts]220for name in fnames:221if os.access(name, os.F_OK | os.X_OK) and not os.path.isdir(name):222return name223return None224
225
226def get_cmake_command():227if IS_WINDOWS:228return "cmake"229
230def _get_version(cmd: Optional[str]) -> Any:231"Returns cmake version."232if cmd is None:233return None234for line in check_output([cmd, "--version"]).decode("utf-8").split("\n"):235if "version" in line:236return LooseVersion(line.strip().split(" ")[2])237raise RuntimeError("no version found")238
239cmake3_version = _get_version(which("cmake3"))240cmake_version = _get_version(which("cmake"))241
242_cmake_min_version = LooseVersion("3.13.0")243if all(244(245ver is None or ver < _cmake_min_version246for ver in [cmake_version, cmake3_version]247)248):249raise RuntimeError("Require cmake or cmake3 3.13.0 or higher but not found")250
251if cmake3_version is None:252cmake_command = "cmake"253elif cmake_version is None:254cmake_command = "cmake3"255else:256if cmake3_version >= cmake_version:257cmake_command = "cmake3"258else:259cmake_command = "cmake"260return cmake_command261
262
263def get_cpack_command():264if IS_WINDOWS:265return "cpack"266if shutil.which("cpack3") is not None:267return "cpack3"268if shutil.which("cpack") is not None:269return "cpack"270else:271raise RuntimeError("no cpack or cpack3 found")272
273
274def get_ipex_git_head_sha(base_dir):275ipex_git_sha = (276subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], cwd=base_dir)277.decode("ascii")278.strip()279)280return ipex_git_sha281
282
283def get_torch_git_head_sha():284if _get_build_target() == "clean":285return None286if _get_build_target() == "cppsdk":287libtorch_hash_file = os.path.join(torch_install_prefix, "build-hash")288if not os.path.exists(libtorch_hash_file):289raise RuntimeError(290"can not find build-hash at {}".format(libtorch_hash_file)291)292with open(libtorch_hash_file, "r") as f:293lines = f.readlines()294for line in lines:295line = line.strip()296if line.isalnum():297return line298raise RuntimeError("can not get libtorch hash in {}".format(libtorch_hash_file))299else:300torch_git_sha = torch.version.git_version301return torch_git_sha302
303
304def get_submodule_commit(base_dir, submodule_dir):305if not os.path.isdir(submodule_dir):306return ""307return (308subprocess.check_output(309["git", "submodule", "status", submodule_dir], cwd=base_dir310)311.decode("ascii")312.strip()313.split()[0]314)315
316
317def get_build_version(ipex_git_sha):318ipex_version = os.getenv("IPEX_VERSION", get_version_num())319if "IPEX_VERSION" not in os.environ:320if _check_env_flag("IPEX_VERSIONED_BUILD", default="1"):321try:322ipex_version += "+git" + ipex_git_sha[:7]323except Exception:324pass325else:326pkg_type = "xpu" if _check_env_flag("BUILD_WITH_XPU") else "cpu"327ipex_version += "+" + pkg_type328return ipex_version329
330
331def write_buffer_to_file(file_path, buffer):332create_if_not_exist(os.path.dirname(file_path))333with open(file_path, "w") as f:334f.write(buffer)335f.close()336
337
338def get_code_fingerprint(ipex_build_version, ipex_git_sha, torch_git_sha, build_type):339fingerprint = "{}_{}_{}_{}".format(340ipex_build_version, ipex_git_sha, torch_git_sha, build_type341)342return fingerprint343
344
345def check_code_fingerprint_in_file(file_path, fingerprint):346b_exist = os.path.isfile(file_path)347if b_exist is False:348return False349
350with open(file_path) as file:351# read all content of a file352content = file.read()353# check if string present in a file354if fingerprint in content:355return True356else:357return False358
359
360def create_version_files(361base_dir,362ipex_build_version,363ipex_git_sha,364torch_git_sha,365gpu_onednn_sha,366cpu_ideep_sha,367):368print(369"Building Intel Extension for PyTorch. Version: {}".format(ipex_build_version)370)371py_version_path = os.path.join(base_dir, PACKAGE_NAME, "_version.py")372cpp_version_path = os.path.join(373base_dir, PACKAGE_NAME, "..", "csrc", "utils", "version.h"374)375build_type_str = get_build_type()376# Check code fingerprint to avoid non-modify rebuild.377current_code_fingerprint = get_code_fingerprint(378ipex_build_version, ipex_git_sha, torch_git_sha, build_type_str379)380
381b_same_fingerprint = check_code_fingerprint_in_file(382py_version_path, current_code_fingerprint383)384if b_same_fingerprint is False:385py_buffer = "# Autogenerated file, do not edit!\n"386py_buffer += "# code fingerprint:\n"387py_buffer += "# {}\n\n".format(current_code_fingerprint)388py_buffer += '__version__ = "{}"\n'.format(ipex_build_version)389py_buffer += '__ipex_gitrev__ = "{}"\n'.format(ipex_git_sha)390py_buffer += '__torch_gitrev__ = "{}"\n'.format(391"" if build_type_str == "Release" else torch_git_sha392)393py_buffer += '__gpu_onednn_gitrev__ = "{}"\n'.format(gpu_onednn_sha)394py_buffer += '__cpu_ideep_gitrev__ = "{}"\n'.format(cpu_ideep_sha)395py_buffer += '__build_type__ = "{}"\n'.format(build_type_str)396
397write_buffer_to_file(py_version_path, py_buffer)398
399b_same_fingerprint = check_code_fingerprint_in_file(400cpp_version_path, current_code_fingerprint401)402if b_same_fingerprint is False:403c_buffer = "// Autogenerated file, do not edit!\n"404c_buffer += "// clang-format off\n"405c_buffer += "// code fingerprint: {}\n".format(current_code_fingerprint)406c_buffer += "// clang-format on\n\n"407c_buffer += "#pragma once\n"408c_buffer += "#include <string>\n\n"409c_buffer += "namespace torch_ipex {\n\n"410c_buffer += "const std::string __version__()\n"411c_buffer += '{{ return "{}"; }}\n\n'.format(ipex_build_version)412c_buffer += "const std::string __gitrev__()\n"413c_buffer += '{{ return "{}"; }}\n\n'.format(ipex_git_sha)414c_buffer += "const std::string __torch_gitrev__()\n"415c_buffer += '{{ return "{}"; }}\n\n'.format(torch_git_sha)416c_buffer += "const std::string __build_type__()\n"417c_buffer += '{{ return "{}"; }}\n\n'.format(build_type_str)418c_buffer += "} // namespace torch_ipex\n"419
420write_buffer_to_file(cpp_version_path, c_buffer)421
422
423def get_project_dir():424project_root_dir = os.path.dirname(__file__)425return os.path.abspath(project_root_dir)426
427
428def get_build_dir():429return os.path.join(get_project_dir(), "build")430
431
432def get_build_type_dir():433build_type_dir = os.path.join(get_build_dir(), get_build_type())434create_if_not_exist(build_type_dir)435return build_type_dir436
437
438def get_package_base_dir():439return os.path.join(get_build_type_dir(), "packages")440
441
442def get_package_dir():443return os.path.join(get_package_base_dir(), PACKAGE_NAME)444
445
446def get_package_lib_dir():447package_lib_dir = os.path.join(get_package_dir(), "lib")448create_if_not_exist(package_lib_dir)449return package_lib_dir450
451
452def get_ipex_cpu_dir():453cpu_root_dir = os.path.join(get_project_dir(), "csrc", "cpu")454return os.path.abspath(cpu_root_dir)455
456
457def get_ipex_cpu_build_dir():458cpu_build_dir = os.path.join(get_build_type_dir(), "csrc", "cpu")459create_if_not_exist(cpu_build_dir)460return cpu_build_dir461
462
463def get_xpu_project_dir():464project_root_dir = os.path.abspath(os.path.dirname(__file__))465return os.path.join(project_root_dir)466
467
468def get_xpu_project_build_dir():469xpu_build_dir = os.path.join(get_build_type_dir(), "csrc", "gpu")470create_if_not_exist(xpu_build_dir)471return xpu_build_dir472
473
474def get_xpu_compliers():475if shutil.which("icx") is None or shutil.which("icpx") is None:476raise RuntimeError("Failed to find compiler path from OS PATH")477if IS_WINDOWS:478return "icx", "icx"479else:480return "icx", "icpx"481
482
483def get_cpu_compliers():484if shutil.which("icx") is None or shutil.which("icpx") is None:485# For CPU build, Intel Compiler is optional.486return None, None487if IS_WINDOWS:488return "icx", "icx"489else:490return "icx", "icpx"491
492
493def get_ipex_python_dir():494project_root_dir = os.path.dirname(__file__)495python_root_dir = os.path.join(project_root_dir, PACKAGE_NAME, "csrc")496return os.path.abspath(python_root_dir)497
498
499def get_ipex_python_build_dir():500python_build_dir = os.path.join(get_build_type_dir(), PACKAGE_NAME, "csrc")501create_if_not_exist(python_build_dir)502return python_build_dir503
504
505def get_ipex_cppsdk_build_dir():506cppsdk_build_dir = os.path.join(get_build_type_dir(), "csrc", "cppsdk")507create_if_not_exist(cppsdk_build_dir)508return cppsdk_build_dir509
510
511base_dir = os.path.dirname(os.path.abspath(__file__))512# Generate version info (ipex.__version__)
513torch_git_sha = get_torch_git_head_sha()514ipex_git_sha = get_ipex_git_head_sha(base_dir)515ipex_build_version = get_build_version(ipex_git_sha)516ipex_gpu_onednn_git_sha = get_submodule_commit(base_dir, "third_party/oneDNN")517ipex_cpu_ideep_git_sha = get_submodule_commit(base_dir, "third_party/ideep")518create_version_files(519base_dir,520ipex_build_version,521ipex_git_sha,522torch_git_sha,523ipex_gpu_onednn_git_sha,524ipex_cpu_ideep_git_sha,525)
526
527
528def auto_format_python_code():529script_path = os.path.join(base_dir, "scripts", "tools", "setup", "flake8.py")530script_cmd = ["python"]531script_cmd.append(script_path)532subprocess.call(533script_cmd,534cwd=base_dir,535)536
537
538# global setup modules
539class IPEXClean(distutils.command.clean.clean, object):540def run(self):541import glob542import re543
544with open(".gitignore", "r") as f:545ignores = f.read()546pat = re.compile(r"^#( BEGIN NOT-CLEAN-FILES )?")547for wildcard in filter(None, ignores.split("\n")):548match = pat.match(wildcard)549if match:550if match.group(1):551# Marker is found and stop reading .gitignore.552break553# Ignore lines which begin with '#'.554else:555for filename in glob.glob(wildcard):556try:557os.remove(filename)558except OSError:559shutil.rmtree(filename, ignore_errors=True)560
561# It's an old-style class in Python 2.7...562distutils.command.clean.clean.run(self)563
564
565def get_cpp_test_dir():566project_root_dir = os.path.abspath(os.path.dirname(__file__))567return os.path.join(project_root_dir, "tests", "cpu", "cpp")568
569
570def get_cpp_test_build_dir():571cpp_test_build_dir = os.path.join(get_build_type_dir(), "tests", "cpu", "cpp")572create_if_not_exist(cpp_test_build_dir)573return cpp_test_build_dir574
575
576def get_pybind11_abi_compiler_flags():577pybind11_abi_flags = []578for pname in ["COMPILER_TYPE", "STDLIB", "BUILD_ABI"]:579pval = getattr(torch._C, f"_PYBIND11_{pname}")580if pval is not None:581pybind11_abi_flags.append(f'-DPYBIND11_{pname}=\\"{pval}\\"')582cl_flags = ""583for flag in pybind11_abi_flags:584cl_flags += flag + " "585return cl_flags586
587
588def _gen_build_cfg_from_cmake(589cmake_exec,590project_root_dir,591cmake_args,592build_dir,593build_env,594use_ninja=True,595build_gpu=False,596):597if IS_WINDOWS:598if use_ninja:599check_call(600[cmake_exec, project_root_dir, "-GNinja"] + cmake_args,601cwd=build_dir,602env=build_env,603)604else:605# using MSVC generator606if build_gpu:607check_call(608[609cmake_exec,610project_root_dir,611"-G Visual Studio 17 2022",612"-T Intel C++ Compiler 2024",613]614+ cmake_args,615cwd=build_dir,616env=build_env,617)618else:619check_call(620[621cmake_exec,622project_root_dir,623"-G Visual Studio 17 2022",624"-T Intel C++ Compiler 2024",625]626+ cmake_args,627cwd=build_dir,628env=build_env,629)630else:631# Linux632check_call(633[cmake_exec, project_root_dir] + cmake_args, cwd=build_dir, env=build_env634)635
636
637def _build_project(build_args, build_dir, build_env, use_ninja=True):638if IS_WINDOWS:639if use_ninja:640check_call(["ninja"] + build_args, cwd=build_dir, env=build_env)641else:642# Current Windows MSVC needs manual build643pass644else:645# Linux646if use_ninja:647check_call(["ninja"] + build_args, cwd=build_dir, env=build_env)648else:649check_call(["make"] + build_args, cwd=build_dir, env=build_env)650
651
652def define_build_options(args, **kwargs):653for key, value in sorted(kwargs.items()):654if value is not None:655args.append("-D{}={}".format(key, value))656
657
658class IPEXCPPLibBuild(build_clib, object):659def run(self):660self.build_lib = os.path.relpath(get_package_dir())661self.build_temp = os.path.relpath(get_build_type_dir())662
663auto_format_python_code()664
665cmake_exec = get_cmake_command()666if cmake_exec is None:667raise RuntimeError(668"CMake must be installed to build the following extensions: "669+ ", ".join(e.name for e in self.extensions)670)671self.cmake = cmake_exec672
673project_root_dir = get_project_dir()674build_type_dir = get_build_type_dir()675
676ipex_python_dir = get_ipex_python_dir()677ipex_python_build_dir = get_ipex_python_build_dir()678
679ipex_cpu_dir = get_ipex_cpu_dir()680ipex_cpu_build_dir = get_ipex_cpu_build_dir()681
682ipex_xpu_dir = get_xpu_project_dir()683ipex_xpu_build_dir = get_xpu_project_build_dir()684
685ipex_cppsdk_build_dir = get_ipex_cppsdk_build_dir()686cpack_out_file = os.path.abspath(687os.path.join(build_type_dir, "IPEXCPackConfig.cmake")688)689self_extract_script = "gen_self_extract.sh"690
691if _get_build_target() == "cppsdk":692cmake_prefix_path = torch_install_prefix693else:694cmake_prefix_path = torch.utils.cmake_prefix_path695
696build_option_common = {697"CMAKE_BUILD_TYPE": get_build_type(),698"CMAKE_INSTALL_LIBDIR": "lib",699"CMAKE_PREFIX_PATH": cmake_prefix_path,700"CMAKE_INSTALL_PREFIX": os.path.abspath(get_package_dir()),701"CMAKE_PROJECT_VERSION": get_version_num(),702"PYTHON_PLATFORM_INFO": platform.platform(),703"PYTHON_INCLUDE_DIR": sysconfig.get_paths()["include"],704"PYTHON_EXECUTABLE": sys.executable,705"IPEX_PROJ_NAME": PACKAGE_NAME,706"LIBIPEX_GITREV": ipex_git_sha,707"LIBIPEX_VERSION": ipex_build_version,708}709
710build_with_cpu = True # Default ON711build_with_xpu = False # Default OFF712
713use_ninja = False714# Windows uses Ninja as default generator715if IS_WINDOWS:716use_ninja = True717sequential_build = False718
719cmake_common_args = []720my_env = os.environ.copy()721
722for var, val in my_env.items():723if var.startswith(("BUILD_", "USE_", "CMAKE_")):724if var == "CMAKE_PREFIX_PATH":725# XXX: Do NOT overwrite CMAKE_PREFIX_PATH. Append into the list, instead!726build_option_common[var] = ";".join(727[build_option_common[var], val.replace(":", ";")]728)729continue730if var == "USE_NINJA" and val.upper() in ON_ENV_VAL:731use_ninja = True732cmake_common_args.append("-GNinja")733continue734if IS_WINDOWS and var == "USE_MSVC" and val.upper() in ON_ENV_VAL:735use_ninja = False736continue737if var == "BUILD_STATS" and val.upper() in ON_ENV_VAL:738sequential_build = True739# fall through740if var == "BUILD_WITH_XPU" and val.upper() in ON_ENV_VAL:741build_with_xpu = True742# fall through743if var == "BUILD_WITH_CPU" and val.upper() in OFF_ENV_VAL:744build_with_cpu = False745# fall through746build_option_common[var] = val747
748define_build_options(cmake_common_args, **build_option_common)749
750nproc = min(int(os.environ.get("MAX_JOBS", os.cpu_count())), os.cpu_count())751if sequential_build:752nproc = 1753print("WARNING: Practice as sequential build with single process !")754
755build_args = ["-j", str(nproc), "install"]756if _check_env_flag("VERBOSE") and use_ninja:757build_args.append("-v")758
759if build_with_xpu:760# Generate cmake for XPU module:761if os.path.isdir(ipex_xpu_dir) is False:762raise RuntimeError(763"It maybe CPU only branch, and it is not contains XPU code."764)765
766gpu_cc, gpu_cxx = get_xpu_compliers()767build_option_gpu = {768**build_option_common,769"BUILD_MODULE_TYPE": "GPU",770"CMAKE_C_COMPILER": gpu_cc,771"CMAKE_CXX_COMPILER": gpu_cxx,772}773
774if get_build_type() == "Debug":775build_option_gpu = {776**build_option_gpu,777"BUILD_SEPARATE_OPS": "ON",778"USE_SYCL_ASSERT": "ON",779"USE_ITT_ANNOTATION": "ON",780}781
782cmake_args_gpu = []783define_build_options(cmake_args_gpu, **build_option_gpu)784_gen_build_cfg_from_cmake(785cmake_exec,786project_root_dir,787cmake_args_gpu,788ipex_xpu_build_dir,789my_env,790use_ninja=use_ninja,791build_gpu=True,792)793
794if build_with_cpu:795# Generate cmake for CPU module:796cpu_cc, cpu_cxx = get_cpu_compliers()797if cpu_cc is not None and cpu_cxx is not None:798build_option_cpu = {799**build_option_common,800"BUILD_MODULE_TYPE": "CPU",801"CMAKE_C_COMPILER": cpu_cc,802"CMAKE_CXX_COMPILER": cpu_cxx,803}804else:805build_option_cpu = {**build_option_common, "BUILD_MODULE_TYPE": "CPU"}806
807cmake_args_cpu = []808define_build_options(cmake_args_cpu, **build_option_cpu)809_gen_build_cfg_from_cmake(810cmake_exec,811project_root_dir,812cmake_args_cpu,813ipex_cpu_build_dir,814my_env,815use_ninja=use_ninja,816)817
818# Generate cmake for the CPP UT819build_option_cpp_test = {820**build_option_common,821"PROJECT_DIR": project_root_dir,822"PYTORCH_INSTALL_DIR": pytorch_install_dir,823"CPP_TEST_BUILD_DIR": get_cpp_test_build_dir(),824}825
826cmake_args_cpp_test = []827define_build_options(cmake_args_cpp_test, **build_option_cpp_test)828_gen_build_cfg_from_cmake(829cmake_exec,830get_cpp_test_dir(),831cmake_args_cpp_test,832get_cpp_test_build_dir(),833my_env,834use_ninja=use_ninja,835)836
837if _get_build_target() in ["develop", "python"]:838# Generate cmake for common python module:839build_option_python = {840**build_option_common,841"BUILD_MODULE_TYPE": "PYTHON",842"PYBIND11_CL_FLAGS": get_pybind11_abi_compiler_flags(),843}844
845cmake_args_python = []846define_build_options(cmake_args_python, **build_option_python)847_gen_build_cfg_from_cmake(848cmake_exec,849project_root_dir,850cmake_args_python,851ipex_python_build_dir,852my_env,853use_ninja=use_ninja,854)855
856elif _get_build_target() == "cppsdk":857# Generate cmake for CPPSDK package:858build_option_cppsdk = {859**build_option_common,860"BUILD_MODULE_TYPE": "CPPSDK",861"CPACK_CONFIG_FILE": cpack_out_file,862"CPACK_OUTPUT_DIR": build_type_dir,863"LIBIPEX_GEN_SCRIPT": self_extract_script,864}865
866cmake_args_cppsdk = []867define_build_options(cmake_args_cppsdk, **build_option_cppsdk)868_gen_build_cfg_from_cmake(869cmake_exec,870project_root_dir,871cmake_args_cppsdk,872ipex_cppsdk_build_dir,873my_env,874use_ninja=use_ninja,875)876
877if build_with_xpu:878# Build XPU module:879_build_project(build_args, ipex_xpu_build_dir, my_env, use_ninja=use_ninja)880
881if build_with_cpu:882# Build CPU module:883_build_project(build_args, ipex_cpu_build_dir, my_env, use_ninja=use_ninja)884
885# Build the CPP UT886_build_project(887build_args, get_cpp_test_build_dir(), my_env, use_ninja=use_ninja888)889
890if _get_build_target() in ["develop", "python"]:891# Build common python module:892_build_project(893build_args, ipex_python_build_dir, my_env, use_ninja=use_ninja894)895
896elif _get_build_target() == "cppsdk":897# Build CPPSDK package:898_build_project(899build_args, ipex_cppsdk_build_dir, my_env, use_ninja=use_ninja900)901cpack_exec = get_cpack_command()902check_call([cpack_exec, "--config", cpack_out_file])903gen_script_path = os.path.abspath(904os.path.join(build_type_dir, self_extract_script)905)906if not os.path.isfile(gen_script_path):907raise "Cannot find script to generate self-extract package in {}".format(908gen_script_path
909)910check_call(gen_script_path, shell=True)911
912# Copy the export library, header and cmake file to root/intel_extension_for_pytorch dir.913# It is only copied in "develop" mode, which can save disk space in "install" mode.914if _get_build_target() == "develop":915ret = get_src_lib_and_dst()916for src, dst in ret:917self.copy_file(src, dst)918
919
920def get_src_lib_and_dst():921ret = []922generated_cpp_files = glob.glob(923os.path.join(get_package_base_dir(), PACKAGE_NAME, "lib", "**/*.so"),924recursive=True,925)926generated_cpp_files.extend(927glob.glob(928os.path.join(get_package_base_dir(), PACKAGE_NAME, "bin", "**/*.dll"),929recursive=True,930)931)932generated_cpp_files.extend(933glob.glob(934os.path.join(get_package_base_dir(), PACKAGE_NAME, "lib", "**/*.lib"),935recursive=True,936)937)938generated_cpp_files.extend(939glob.glob(940os.path.join(get_package_base_dir(), PACKAGE_NAME, "include", "**/*.h"),941recursive=True,942)943)944generated_cpp_files.extend(945glob.glob(946os.path.join(get_package_base_dir(), PACKAGE_NAME, "share", "**/*.cmake"),947recursive=True,948)949)950for src in generated_cpp_files:951dst = os.path.join(952get_project_dir(),953PACKAGE_NAME,954os.path.relpath(src, os.path.join(get_package_base_dir(), PACKAGE_NAME)),955)956dst_path = Path(dst)957if not dst_path.parent.exists():958Path(dst_path.parent).mkdir(parents=True, exist_ok=True)959ret.append((src, dst))960return ret961
962
963def get_src_py_and_dst():964ret = []965generated_python_files = glob.glob(966os.path.join(get_project_dir(), PACKAGE_NAME, "**/*.py"), recursive=True967)968for src in generated_python_files:969dst = os.path.join(970get_package_base_dir(),971PACKAGE_NAME,972os.path.relpath(src, os.path.join(get_project_dir(), PACKAGE_NAME)),973)974dst_path = Path(dst)975if not dst_path.parent.exists():976Path(dst_path.parent).mkdir(parents=True, exist_ok=True)977ret.append((src, dst))978return ret979
980
981# python specific setup modules
982class IPEXEggInfoBuild(egg_info, object):983def finalize_options(self):984super(IPEXEggInfoBuild, self).finalize_options()985
986
987class IPEXInstallCmd(install, object):988def finalize_options(self):989self.build_lib = os.path.relpath(get_package_base_dir())990return super(IPEXInstallCmd, self).finalize_options()991
992
993class IPEXPythonPackageBuild(build_py, object):994def run(self) -> None:995ret = get_src_py_and_dst()996for src, dst in ret:997self.copy_file(src, dst)998super(IPEXPythonPackageBuild, self).finalize_options()999
1000
1001def make_relative_rpath(path):1002if IS_DARWIN:1003return "-Wl,-rpath,@loader_path/" + path1004elif IS_WINDOWS:1005return path1006else:1007return "-Wl,-rpath,$ORIGIN/" + path1008
1009
1010def pyi_module():1011main_libraries = ["intel-ext-pt-python"]1012main_sources = [os.path.join(PACKAGE_NAME, "csrc", "_C.cpp")]1013
1014include_dirs = [1015os.path.realpath("."),1016os.path.realpath(os.path.join(PACKAGE_NAME, "csrc")),1017os.path.join(pytorch_install_dir, "include"),1018os.path.join(pytorch_install_dir, "include", "torch", "csrc", "api", "include"),1019]1020
1021library_dirs = ["lib", os.path.join(pytorch_install_dir, "lib")]1022
1023if not IS_WINDOWS:1024library_dirs = ["lib", os.path.join(pytorch_install_dir, "lib")]1025
1026extra_compile_args = [1027"-Wall",1028"-Wextra",1029"-Wno-strict-overflow",1030"-Wno-unused-parameter",1031"-Wno-missing-field-initializers",1032"-Wno-write-strings",1033"-Wno-unknown-pragmas",1034# This is required for Python 2 declarations that are deprecated in 3.1035"-Wno-deprecated-declarations",1036# Python 2.6 requires -fno-strict-aliasing, see1037# http://legacy.python.org/dev/peps/pep-3123/1038# We also depend on it in our code (even Python 3).1039"-fno-strict-aliasing",1040# Clang has an unfixed bug leading to spurious missing1041# braces warnings, see1042# https://bugs.llvm.org/show_bug.cgi?id=216291043"-Wno-missing-braces",1044]1045
1046C_ext = CppExtension(1047"{}._C".format(PACKAGE_NAME),1048libraries=main_libraries,1049sources=main_sources,1050language="c++",1051extra_compile_args=extra_compile_args,1052include_dirs=include_dirs,1053library_dirs=library_dirs,1054extra_link_args=[make_relative_rpath("lib")],1055)1056else:1057library_dirs = ["bin", os.path.join(pytorch_install_dir, "lib")]1058extra_link_args = ["/NODEFAULTLIB:LIBCMT.LIB"]1059# /MD links against DLL runtime1060# and matches the flags set for protobuf and ONNX1061# /EHsc is about standard C++ exception handling1062# /DNOMINMAX removes builtin min/max functions1063# /wdXXXX disables warning no. XXXX1064extra_compile_args = [1065"/MD",1066"/EHsc",1067"/DNOMINMAX",1068"/wd4267",1069"/wd4251",1070"/wd4522",1071"/wd4522",1072"/wd4838",1073"/wd4305",1074"/wd4244",1075"/wd4190",1076"/wd4101",1077"/wd4996",1078"/wd4275",1079]1080C_ext = CppExtension(1081"{}._C".format(PACKAGE_NAME),1082libraries=main_libraries,1083sources=main_sources,1084language="c++",1085extra_compile_args=extra_compile_args,1086include_dirs=include_dirs,1087library_dirs=library_dirs,1088extra_link_args=extra_link_args,1089)1090return C_ext1091
1092
1093def pyi_isa_help_module():1094main_libraries = []1095main_sources = [1096os.path.join(PACKAGE_NAME, "csrc", "_isa_help_main.cpp"),1097os.path.join(PACKAGE_NAME, "csrc", "cpu", "isa_help", "isa_help.cpp"),1098os.path.join("csrc", "cpu", "isa", "cpu_feature.cpp"),1099]1100
1101include_dirs = [1102os.path.realpath("."),1103os.path.realpath(os.path.join("csrc", "cpu", "isa")),1104os.path.realpath(os.path.join(PACKAGE_NAME, "csrc")),1105os.path.join(pytorch_install_dir, "include"),1106os.path.join(pytorch_install_dir, "include", "torch", "csrc", "api", "include"),1107]1108
1109if not IS_WINDOWS:1110library_dirs = ["lib", os.path.join(pytorch_install_dir, "lib")]1111
1112extra_compile_args = [1113"-Wall",1114"-Wextra",1115"-Wno-strict-overflow",1116"-Wno-unused-parameter",1117"-Wno-missing-field-initializers",1118"-Wno-write-strings",1119"-Wno-unknown-pragmas",1120# This is required for Python 2 declarations that are deprecated in 3.1121"-Wno-deprecated-declarations",1122# Python 2.6 requires -fno-strict-aliasing, see1123# http://legacy.python.org/dev/peps/pep-3123/1124# We also depend on it in our code (even Python 3).1125"-fno-strict-aliasing",1126# Clang has an unfixed bug leading to spurious missing1127# braces warnings, see1128# https://bugs.llvm.org/show_bug.cgi?id=216291129"-Wno-missing-braces",1130]1131
1132C_ext = CppExtension(1133"{}._isa_help".format(PACKAGE_NAME),1134libraries=main_libraries,1135sources=main_sources,1136language="c++",1137extra_compile_args=extra_compile_args,1138include_dirs=include_dirs,1139library_dirs=library_dirs,1140extra_link_args=[make_relative_rpath("lib")],1141)1142else:1143library_dirs = ["bin", os.path.join(pytorch_install_dir, "lib")]1144extra_link_args = ["/NODEFAULTLIB:LIBCMT.LIB"]1145# /MD links against DLL runtime1146# and matches the flags set for protobuf and ONNX1147# /EHsc is about standard C++ exception handling1148# /DNOMINMAX removes builtin min/max functions1149# /wdXXXX disables warning no. XXXX1150extra_compile_args = [1151"/MD",1152"/EHsc",1153"/DNOMINMAX",1154"/wd4267",1155"/wd4251",1156"/wd4522",1157"/wd4522",1158"/wd4838",1159"/wd4305",1160"/wd4244",1161"/wd4190",1162"/wd4101",1163"/wd4996",1164"/wd4275",1165]1166C_ext = CppExtension(1167"{}._isa_help".format(PACKAGE_NAME),1168libraries=main_libraries,1169sources=main_sources,1170language="c++",1171extra_compile_args=extra_compile_args,1172include_dirs=include_dirs,1173library_dirs=library_dirs,1174extra_link_args=extra_link_args,1175)1176return C_ext1177
1178
1179ext_modules = []1180cmdclass = {1181"build_clib": IPEXCPPLibBuild,1182"bdist_cppsdk": IPEXCPPLibBuild,1183"clean": IPEXClean,1184}
1185
1186
1187def fill_python_target_cmd(cmdclass, ext_modules):1188class IPEXExtBuild(BuildExtension):1189def run(self):1190self.run_command("build_clib")1191
1192self.build_lib = os.path.relpath(get_package_base_dir())1193self.build_temp = os.path.relpath(get_build_type_dir())1194self.library_dirs.append(os.path.relpath(get_package_lib_dir()))1195super(IPEXExtBuild, self).run()1196
1197cmdclass["build_ext"] = IPEXExtBuild1198cmdclass["build_py"] = IPEXPythonPackageBuild1199cmdclass["egg_info"] = IPEXEggInfoBuild1200cmdclass["install"] = IPEXInstallCmd1201ext_modules.append(pyi_module())1202ext_modules.append(pyi_isa_help_module())1203
1204
1205if _get_build_target() in ["develop", "python"]:1206fill_python_target_cmd(cmdclass, ext_modules)1207
1208
1209long_description = ""1210this_directory = os.path.abspath(os.path.dirname(__file__))1211with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:1212long_description = f.read()1213
1214entry_points = {1215"console_scripts": [1216"ipexrun = {}.launcher:main".format(PACKAGE_NAME),1217]1218}
1219
1220
1221setup(1222name=PACKAGE_NAME,1223version=ipex_build_version,1224description="Intel® Extension for PyTorch*",1225long_description=long_description,1226long_description_content_type="text/markdown",1227url="https://github.com/intel/intel-extension-for-pytorch",1228author="Intel Corp.",1229install_requires=_build_installation_dependency(),1230packages=[PACKAGE_NAME],1231package_data={PACKAGE_NAME: ["*.so", "lib/*.so", "bin/*.dll", "lib/*.lib"]},1232zip_safe=False,1233ext_modules=ext_modules,1234cmdclass=cmdclass,1235entry_points=entry_points,1236license="https://www.apache.org/licenses/LICENSE-2.0",1237classifiers=[1238"License :: OSI Approved :: Apache Software License",1239],1240)
1241