diff --git a/.github/workflows/conda-package.yml b/.github/workflows/conda-package.yml index 10823ca1a9..59671ec0d2 100644 --- a/.github/workflows/conda-package.yml +++ b/.github/workflows/conda-package.yml @@ -633,7 +633,7 @@ jobs: do pushd $d conda activate --stack ${{ env.BUILD_ENV_NAME }} - CC=icx CXX=icpx python setup.py develop -G Ninja || exit 1 + CC=icx CXX=icpx python setup.py build_ext --inplace -G Ninja || exit 1 conda deactivate python -m pytest tests || exit 1 popd diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml index 85034faf2f..5a385ba6ac 100644 --- a/.github/workflows/generate-docs.yml +++ b/.github/workflows/generate-docs.yml @@ -75,14 +75,8 @@ jobs: source /opt/intel/oneapi/setvars.sh wget https://github.com/vovkos/doxyrest/releases/download/doxyrest-2.1.2/doxyrest-2.1.2-linux-amd64.tar.xz tar xf doxyrest-2.1.2-linux-amd64.tar.xz - python setup.py develop -G Ninja --build-type=Release \ - -- \ - -DCMAKE_C_COMPILER:PATH=$(which icx) \ - -DCMAKE_CXX_COMPILER:PATH=$(which icpx) \ - -DDPCTL_GENERATE_DOCS=ON \ - -DDPCTL_ENABLE_DOXYREST=ON \ - -DDoxyrest_DIR=`pwd`/doxyrest-2.1.2-linux-amd64 \ - -DCMAKE_VERBOSE_MAKEFILE=ON + python scripts/gen_docs.py --c-compiler=$(which icx) --cxx-compiler=$(which icpx) \ + --doxyrest-root=`pwd`/doxyrest-2.1.2-linux-amd64 --verbose || exit 1 python -c "import dpctl; print(dpctl.__version__)" || exit 1 pushd "$(find _skbuild -name cmake-build)" || exit 1 cmake --build . --target Sphinx || exit 1 diff --git a/.github/workflows/os-llvm-sycl-build.yml b/.github/workflows/os-llvm-sycl-build.yml index 3cc39bebf7..793e057e8f 100644 --- a/.github/workflows/os-llvm-sycl-build.yml +++ b/.github/workflows/os-llvm-sycl-build.yml @@ -146,7 +146,8 @@ jobs: shell: bash -l {0} run: | source set_allvars.sh - CC=clang CXX=clang++ python setup.py develop -G Ninja + python scripts/build_locally.py --c-compiler=clang --cxx-compiler=clang++ \ + --compiler-root=${SYCL_BUNDLE_FOLDER}/dpcpp_compiler/bin || exit 1 - name: Run lsplatforms shell: bash -l {0} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f6afd937d4..2dca171a62 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -203,11 +203,8 @@ To check the code coverage for your code, follow these steps: coverage html ``` - The code coverage builds the C sources with debug symbols. For this - reason, the coverage script builds the package in `develop` mode of - `setup.py`. - - The coverage results for the C and Python sources are printed to the + The code coverage builds the C sources with debug symbols, and the + coverage results for the C and Python sources are printed to the terminal during the build (`libsyclinterface`) and pytest execution (Python). The detailed coverage reports for the `libsyclinterface` library are saved to the `dpctl-c-api-coverage` directory. The Python coverage reports are saved to diff --git a/docs/doc_sources/contributor_guides/building.rst b/docs/doc_sources/contributor_guides/building.rst index b1fec6d2b8..f1681c6c6a 100644 --- a/docs/doc_sources/contributor_guides/building.rst +++ b/docs/doc_sources/contributor_guides/building.rst @@ -129,14 +129,16 @@ To develop, run: .. code-block:: bash - python setup.py develop -G Ninja -DCMAKE_C_COMPILER:PATH=icx -DCMAKE_CXX_COMPILER:PATH=icpx + python setup.py build_ext --inplace -G Ninja -DCMAKE_C_COMPILER:PATH=icx -DCMAKE_CXX_COMPILER:PATH=icpx + python -m pip install -e . .. tab-item:: Windows :sync: win .. code-block:: bat - python setup.py develop -G Ninja -DCMAKE_C_COMPILER:PATH=icx -DCMAKE_CXX_COMPILER:PATH=icx + python setup.py build_ext --inplace -G Ninja -DCMAKE_C_COMPILER:PATH=icx -DCMAKE_CXX_COMPILER:PATH=icx + python -m pip install -e . Developing can be streamlined using the driver script: @@ -169,7 +171,8 @@ the relevant CMake variables, for example: .. code-block:: bash - python setup.py develop -- -G Ninja -DCMAKE_C_COMPILER:PATH=$(which clang) -DCMAKE_CXX_COMPILER:PATH=$(which clang++) + python setup.py build_ext --inplace -G Ninja -DCMAKE_C_COMPILER:PATH=$(which clang) -DCMAKE_CXX_COMPILER:PATH=$(which clang++) + python -m pip install -e . Or you can use the driver script: diff --git a/examples/cython/sycl_buffer/README.md b/examples/cython/sycl_buffer/README.md index c66053b618..89d57f0d40 100644 --- a/examples/cython/sycl_buffer/README.md +++ b/examples/cython/sycl_buffer/README.md @@ -14,9 +14,14 @@ oneMKL. > **NOTE:** Make sure oneAPI is activated, $ONEAPI_ROOT must be set. -To compile the example, run: +To compile the example on Linux, run: +```bash +CC=icx CXX=icpx python setup.py build_ext --inplace -G Ninja ``` -python setup.py develop + +On Windows, run: +```bash +CC=icx CXX=icx python setup.py build_ext --inplace -G Ninja ``` ## Running diff --git a/examples/cython/use_dpctl_sycl/README.md b/examples/cython/use_dpctl_sycl/README.md index 8e7df96e56..e6041d12aa 100644 --- a/examples/cython/use_dpctl_sycl/README.md +++ b/examples/cython/use_dpctl_sycl/README.md @@ -9,8 +9,14 @@ written in Cython. ## Building +To build the example on Linux, run: ```bash -python setup.py develop +CC=icx CXX=icpx python setup.py build_ext --inplace -G Ninja +``` + +On Windows, run: +```bash +CC=icx CXX=icx python setup.py build_ext --inplace -G Ninja ``` ## Testing diff --git a/examples/pybind11/onemkl_gemv/README.md b/examples/pybind11/onemkl_gemv/README.md index 104e53dc98..f3b1f2d2b5 100644 --- a/examples/pybind11/onemkl_gemv/README.md +++ b/examples/pybind11/onemkl_gemv/README.md @@ -5,9 +5,9 @@ > **NOTE:** Install scikit-build and dpcpp before next steps. -To build, run: -```sh -python setup.py develop -- -G "Ninja" \ +To build on Linux, run: +```bash +python setup.py build_ext --inplace -- -G "Ninja" \ -DCMAKE_C_COMPILER:PATH=icx \ -DCMAKE_CXX_COMPILER:PATH=icpx \ -DTBB_LIBRARY_DIR=$CONDA_PREFIX/lib \ @@ -16,6 +16,17 @@ python setup.py develop -- -G "Ninja" \ -DTBB_INCLUDE_DIR=${CONDA_PREFIX}/include ``` +To build on Windows, run: +```bash +python setup.py build_ext --inplace -- -G "Ninja" \ + -DCMAKE_C_COMPILER:PATH=icx \ + -DCMAKE_CXX_COMPILER:PATH=icx \ + -DTBB_LIBRARY_DIR=$CONDA_PREFIX/lib \ + -DMKL_LIBRARY_DIR=${CONDA_PREFIX}/lib \ + -DMKL_INCLUDE_DIR=${CONDA_PREFIX}/include \ + -DTBB_INCLUDE_DIR=${CONDA_PREFIX}/include +``` + ## Running To run the example, use: diff --git a/scripts/_build_helper.py b/scripts/_build_helper.py new file mode 100644 index 0000000000..d41567598b --- /dev/null +++ b/scripts/_build_helper.py @@ -0,0 +1,167 @@ +# Data Parallel Control (dpctl) +# +# Copyright 2025 Intel Corporation +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os +import shutil +import subprocess +import sys + + +def resolve_compilers( + oneapi: bool, + c_compiler: str, + cxx_compiler: str, + compiler_root: str, +): + is_linux = "linux" in sys.platform + + if oneapi or ( + c_compiler is None and cxx_compiler is None and compiler_root is None + ): + return "icx", ("icpx" if is_linux else "icx") + + if ( + (c_compiler is None or not os.path.isabs(c_compiler)) + and (cxx_compiler is None or not os.path.isabs(cxx_compiler)) + and (not compiler_root or not os.path.exists(compiler_root)) + ): + raise RuntimeError( + "--compiler-root option must be set when using non-default DPC++ " + "layout unless absolute paths are provided for both compilers" + ) + + # default values + if c_compiler is None: + c_compiler = "icx" + if cxx_compiler is None: + cxx_compiler = "icpx" if is_linux else "icx" + + for name, opt_name in ( + (c_compiler, "--c-compiler"), + (cxx_compiler, "--cxx-compiler"), + ): + if os.path.isabs(name): + path = name + else: + path = os.path.join(compiler_root, name) + if not os.path.exists(path): + raise RuntimeError(f"{opt_name} value {name} not found") + return c_compiler, cxx_compiler + + +def run(cmd: list[str], env: dict[str, str] = None, cwd: str = None): + print("+", " ".join(cmd)) + subprocess.check_call( + cmd, env=env or os.environ.copy(), cwd=cwd or os.getcwd() + ) + + +def capture_cmd_output(cmd: list[str], cwd: str = None): + print("+", " ".join(cmd)) + return ( + subprocess.check_output(cmd, cwd=cwd or os.getcwd()) + .decode("utf-8") + .strip("\n") + ) + + +def err(msg: str, script: str): + raise RuntimeError(f"[{script}] error: {msg}") + + +def log_cmake_args(cmake_args: list[str], script: str): + print(f"[{script}] Using CMake args:\n{' '.join(cmake_args)}") + + +def make_cmake_args( + c_compiler: str = None, + cxx_compiler: str = None, + level_zero: bool = True, + glog: bool = False, + verbose: bool = False, + other_opts: str = None, +): + args = [ + f"-DCMAKE_C_COMPILER:PATH={c_compiler}" if c_compiler else "", + f"-DCMAKE_CXX_COMPILER:PATH={cxx_compiler}" if cxx_compiler else "", + f"-DDPCTL_ENABLE_L0_PROGRAM_CREATION={'ON' if level_zero else 'OFF'}", + f"-DDPCTL_ENABLE_GLOG:BOOL={'ON' if glog else 'OFF'}", + ] + + if verbose: + args.append("-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON") + if other_opts: + args.extend(other_opts.split()) + + return args + + +def build_extension( + setup_dir: str, + env: dict[str, str], + cmake_args: list[str], + cmake_executable: str = None, + generator: str = None, + build_type: str = None, +): + cmd = [sys.executable, "setup.py", "build_ext", "--inplace"] + if cmake_executable: + cmd.append(f"--cmake-executable={cmake_executable}") + if generator: + cmd.append(f"--generator={generator}") + if build_type: + cmd.append(f"--build-type={build_type}") + if cmake_args: + cmd.append("--") + cmd += cmake_args + run( + cmd, + env=env, + cwd=setup_dir, + ) + + +def install_editable(setup_dir: str, env: dict[str, str]): + run( + [ + sys.executable, + "-m", + "pip", + "install", + "-e", + ".", + "--no-build-isolation", + ], + env=env, + cwd=setup_dir, + ) + + +def clean_build_dir(setup_dir: str): + if ( + not isinstance(setup_dir, str) + or not setup_dir + or not os.path.isdir(setup_dir) + ): + raise RuntimeError(f"Invalid setup directory provided: '{setup_dir}'") + target = os.path.join(setup_dir, "_skbuild") + if os.path.exists(target): + print(f"Cleaning build directory: {target}") + try: + shutil.rmtree(target) + except Exception as e: + print(f"Failed to remove build directory: '{target}'") + raise e diff --git a/scripts/build_locally.py b/scripts/build_locally.py index ee76204c08..e88d7cb825 100644 --- a/scripts/build_locally.py +++ b/scripts/build_locally.py @@ -14,225 +14,187 @@ # See the License for the specific language governing permissions and # limitations under the License. +import argparse import os -import subprocess import sys +from _build_helper import ( + build_extension, + clean_build_dir, + err, + install_editable, + log_cmake_args, + make_cmake_args, + resolve_compilers, +) -def run( - use_oneapi=True, - build_type="Release", - c_compiler=None, - cxx_compiler=None, - level_zero=True, - compiler_root=None, - cmake_executable=None, - use_glog=False, - verbose=False, - cmake_opts="", - target_cuda=None, - target_hip=None, -): - build_system = None - - if "linux" in sys.platform: - build_system = "Ninja" - elif sys.platform in ["win32", "cygwin"]: - build_system = "Ninja" - else: - assert False, sys.platform + " not supported" - setup_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - cmake_args = [ - sys.executable, - "setup.py", - "develop", - ] - if cmake_executable: - cmake_args += [ - "--cmake-executable=" + cmake_executable, - ] - cmake_args += [ - "--build-type=" + build_type, - "--generator=" + build_system, - "--", - "-DCMAKE_C_COMPILER:PATH=" + c_compiler, - "-DCMAKE_CXX_COMPILER:PATH=" + cxx_compiler, - "-DDPCTL_ENABLE_L0_PROGRAM_CREATION=" + ("ON" if level_zero else "OFF"), - "-DDPCTL_ENABLE_GLOG:BOOL=" + ("ON" if use_glog else "OFF"), - ] - if verbose: - cmake_args += [ - "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON", - ] - if cmake_opts: - cmake_args += cmake_opts.split() - if target_cuda is not None: - if not target_cuda.strip(): - raise ValueError( - "--target-cuda can not be an empty string. " - "Use --target-cuda= or --target-cuda" - ) - if any(opt.startswith("-DDPCTL_TARGET_CUDA=") for opt in cmake_args): - raise ValueError( - "Both --target-cuda and -DDPCTL_TARGET_CUDA in --cmake-opts " - "were specified. Please use only one method " - "to avoid ambiguity" - ) - cmake_args += [ - f"-DDPCTL_TARGET_CUDA={target_cuda}", - ] - if target_hip is not None: - if not target_hip.strip(): - raise ValueError( - "--target-hip requires an architecture (e.g., gfx90a)" - ) - if any(opt.startswith("-DDPCTL_TARGET_HIP=") for opt in cmake_args): - raise ValueError( - "Both --target-hip and -DDPCTL_TARGET_HIP in --cmake-opts " - "were specified. Please use only one method " - "to avoid ambiguity" - ) - cmake_args += [ - f"-DDPCTL_TARGET_HIP={target_hip}", - ] - subprocess.check_call( - cmake_args, shell=False, cwd=setup_dir, env=os.environ - ) - - -if __name__ == "__main__": - import argparse +def parse_args(): + p = argparse.ArgumentParser(description="Local dpctl build driver") - parser = argparse.ArgumentParser( - description="Driver to build dpctl for in-place installation" + p.add_argument( + "--c-compiler", + type=str, + default=None, + help="Path or name of C compiler", + ) + p.add_argument( + "--cxx-compiler", + type=str, + default=None, + help="Path or name of C++ compiler", ) - driver = parser.add_argument_group(title="Coverage driver arguments") - driver.add_argument("--c-compiler", help="Name of C compiler", default=None) - driver.add_argument( - "--cxx-compiler", help="Name of C++ compiler", default=None + p.add_argument( + "--compiler-root", + type=str, + default=None, + help="Path to compiler installation root", ) - driver.add_argument( + + p.add_argument( "--oneapi", - help="Is one-API installation", dest="oneapi", action="store_true", + help="Use default oneAPI compiler layout", ) - driver.add_argument( + p.add_argument( "--debug", - default="Release", + dest="build_type", const="Debug", action="store_const", - help="Set the compilation mode to debugging", + default="Release", + help="Set build type to Debug (defaults to Release)", ) - driver.add_argument( - "--compiler-root", - type=str, - help="Path to compiler home directory", - default=None, + + p.add_argument( + "--generator", type=str, default="Ninja", help="CMake generator" ) - driver.add_argument( + p.add_argument( "--cmake-executable", type=str, - help="Path to cmake executable", default=None, + help="Path to CMake executable used by build", ) - driver.add_argument( - "--no-level-zero", - help="Enable Level Zero support", - dest="level_zero", - action="store_false", - ) - driver.add_argument( + + p.add_argument( "--glog", - help="DPCTLSyclInterface uses Google logger", dest="glog", action="store_true", + help="Enable DPCTL Google logger support", ) - driver.add_argument( + p.add_argument( "--verbose", - help="Build using vebose makefile mode", dest="verbose", action="store_true", + help="Enable verbose makefile output", + ) + + p.add_argument( + "--no-level-zero", + dest="no_level_zero", + action="store_true", + default=False, + help="Disable Level Zero backend (deprecated: use --target-level-zero " + "OFF)", ) - driver.add_argument( + + p.add_argument( "--cmake-opts", - help="Options to pass through to cmake", - dest="cmake_opts", - default="", type=str, + default="", + help="Additional options to pass directly to CMake", ) - driver.add_argument( + + p.add_argument( "--target-cuda", nargs="?", const="ON", - help="Enable CUDA target for build; " - "optionally specify architecture (e.g., --target-cuda=sm_80)", default=None, - type=str, + help="Enable CUDA build. Architecture is optional to specify.", ) - driver.add_argument( + p.add_argument( "--target-hip", required=False, - help="Enable HIP target for build. " - "Must specify HIP architecture (e.g., --target-hip=gfx90a)", type=str, + help="Enable HIP backend. Architecture required to be specified.", + ) + + p.add_argument( + "--clean", + action="store_true", + help="Remove build dir before rebuild", + ) + p.add_argument( + "--skip-editable", + action="store_true", + help="Skip pip editable install step", + ) + + return p.parse_args() + + +def main(): + if sys.platform not in ["cygwin", "win32", "linux"]: + err(f"{sys.platform} not supported", "build_locally") + args = parse_args() + setup_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + c_compiler, cxx_compiler = resolve_compilers( + args.oneapi, args.c_compiler, args.cxx_compiler, args.compiler_root + ) + + # clean build dir if --clean set + if args.clean: + clean_build_dir(setup_dir) + + # Level Zero state (on unless explicitly disabled) + level_zero_enabled = False if args.no_level_zero else True + + cmake_args = make_cmake_args( + c_compiler=c_compiler, + cxx_compiler=cxx_compiler, + level_zero=level_zero_enabled, + glog=args.glog, + verbose=args.verbose, + other_opts=args.cmake_opts, ) - args = parser.parse_args() - args_to_validate = [ - "c_compiler", - "cxx_compiler", - "compiler_root", + # handle architecture conflicts + if args.target_hip is not None and not args.target_hip.strip(): + err("--target-hip requires an explicit architecture", "build_locally") + + # CUDA/HIP targets + if args.target_cuda: + cmake_args += [f"-DDPCTL_TARGET_CUDA={args.target_cuda}"] + if args.target_hip: + cmake_args += [f"-DDPCTL_TARGET_HIP={args.target_hip}"] + + cmake_args += [ + "-DDPCTL_ENABLE_L0_PROGRAM_CREATION=" + f"{'ON' if level_zero_enabled else 'OFF'}" ] - if args.oneapi or ( - args.c_compiler is None - and args.cxx_compiler is None - and args.compiler_root is None - ): - args.c_compiler = "icx" - args.cxx_compiler = "icpx" if "linux" in sys.platform else "icx" - args.compiler_root = None - else: - cr = args.compiler_root - if isinstance(cr, str) and os.path.exists(cr): - if args.c_compiler is None: - args.c_compiler = "icx" - if args.cxx_compiler is None: - args.cxx_compiler = "icpx" if "linux" in sys.platform else "icx" - else: - raise RuntimeError( - "Option 'compiler-root' must be provided when " - "using non-default DPC++ layout." - ) - args_to_validate = [ - "c_compiler", - "cxx_compiler", - ] - for p in args_to_validate: - arg = getattr(args, p) - assert isinstance(arg, str) - if not os.path.exists(arg): - arg2 = os.path.join(cr, arg) - if os.path.exists(arg2): - arg = arg2 - setattr(args, p, arg) - if not os.path.exists(arg): - opt_name = p.replace("_", "-") - raise RuntimeError(f"Option {opt_name} value {arg} must exist.") - - run( - use_oneapi=args.oneapi, - build_type=args.debug, - c_compiler=args.c_compiler, - cxx_compiler=args.cxx_compiler, - level_zero=args.level_zero, - compiler_root=args.compiler_root, + log_cmake_args(cmake_args, "build_locally") + + print("[build_locally] Building extensions in-place...") + + env = os.environ.copy() + + build_extension( + setup_dir, + env, + cmake_args, cmake_executable=args.cmake_executable, - use_glog=args.glog, - verbose=args.verbose, - cmake_opts=args.cmake_opts, - target_cuda=args.target_cuda, - target_hip=args.target_hip, + generator=args.generator, + build_type=args.build_type, ) + if not args.skip_editable: + install_editable(setup_dir, env) + else: + print("[build_locally] Skipping editable install (--skip-editable)") + + print("[build_locally] Build complete") + + +if __name__ == "__main__": + main() diff --git a/scripts/gen_coverage.py b/scripts/gen_coverage.py index bdc2bd931c..88ab13ee5b 100644 --- a/scripts/gen_coverage.py +++ b/scripts/gen_coverage.py @@ -14,66 +14,178 @@ # See the License for the specific language governing permissions and # limitations under the License. +import argparse import os import re import subprocess import sys import sysconfig +from _build_helper import ( + build_extension, + capture_cmd_output, + clean_build_dir, + err, + install_editable, + log_cmake_args, + make_cmake_args, + resolve_compilers, + run, +) -def run( - use_oneapi=True, - c_compiler=None, - cxx_compiler=None, - level_zero=True, - compiler_root=None, - run_pytest=False, - bin_llvm=None, - gtest_config=None, - verbose=False, -): - IS_LIN = False - - if "linux" in sys.platform: - IS_LIN = True - elif sys.platform in ["win32", "cygwin"]: - pass + +def find_bin_llvm(compiler): + if os.path.isabs(compiler): + bin_dir = os.path.dirname(compiler) + else: + compiler_path = capture_cmd_output(["which", compiler]) + if not compiler_path: + raise RuntimeError(f"Compiler {compiler} not found in PATH") + bin_dir = os.path.dirname(compiler_path) + compiler_dir = os.path.join(bin_dir, "compiler") + if os.path.exists(compiler_dir): + bin_llvm = compiler_dir else: - assert False, sys.platform + " not supported" + bin_dir = os.path.dirname(bin_dir) + bin_llvm = os.path.join(bin_dir, "bin-llvm") + if not os.path.exists(bin_llvm): + raise RuntimeError(f"--bin-llvm value {bin_llvm} not found") + return bin_llvm - if not IS_LIN: - raise RuntimeError( - "This scripts only supports coverage collection on Linux" - ) + +def parse_args(): + p = argparse.ArgumentParser(description="Build dpctl and generate coverage") + + p.add_argument( + "--c-compiler", default=None, help="Path or name of C compiler" + ) + p.add_argument( + "--cxx-compiler", default=None, help="Path or name of C++ compiler" + ) + p.add_argument( + "--compiler-root", + type=str, + default=None, + help="Path to compiler installation root", + ) + p.add_argument( + "--oneapi", + dest="oneapi", + action="store_true", + help="Use default oneAPI compiler layout", + ) + + p.add_argument( + "--verbose", + dest="verbose", + action="store_true", + help="Enable verbose makefile output", + ) + + p.add_argument( + "--no-level-zero", + dest="no_level_zero", + action="store_true", + default=False, + help="Disable Level Zero backend (deprecated: use --target-level-zero " + "OFF)", + ) + + p.add_argument( + "--generator", type=str, default="Ninja", help="CMake generator" + ) + p.add_argument( + "--cmake-executable", + type=str, + default=None, + help="Path to CMake executable used by build", + ) + + p.add_argument( + "--cmake-opts", + type=str, + default="", + help="Additional options to pass directly to CMake", + ) + + p.add_argument( + "--gtest-config", + type=str, + help="Path to GTestConfig.cmake file for a custom GTest installation", + ) + p.add_argument( + "--bin-llvm", + type=str, + help="Path to folder where llvm-cov/llvm-profdata can be found", + ) + p.add_argument( + "--skip-pytest", + dest="run_pytest", + action="store_false", + help="Skip running pytest and coverage generation", + ) + p.add_argument( + "--clean", + action="store_true", + help="Remove build dir before rebuild (default: False)", + ) + + return p.parse_args() + + +def main(): + is_linux = "linux" in sys.platform + if not is_linux: + err(f"{sys.platform} not supported", "gen_coverage") + args = parse_args() setup_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - cmake_args = [ - sys.executable, - "setup.py", - "develop", - "--build-type=Coverage", - "--generator=Ninja", - "--", - "-DCMAKE_C_COMPILER:PATH=" + c_compiler, - "-DCMAKE_CXX_COMPILER:PATH=" + cxx_compiler, - "-DDPCTL_ENABLE_L0_PROGRAM_CREATION=" + ("ON" if level_zero else "OFF"), - "-DDPCTL_GENERATE_COVERAGE=ON", - "-DDPCTL_BUILD_CAPI_TESTS=ON", - "-DDPCTL_COVERAGE_REPORT_OUTPUT_DIR=" + setup_dir, - ] - env = dict() + + c_compiler, cxx_compiler = resolve_compilers( + args.oneapi, + args.c_compiler, + args.cxx_compiler, + args.compiler_root, + ) + bin_llvm = find_bin_llvm(c_compiler) + + if args.clean: + clean_build_dir(setup_dir) + + # Level Zero state (on unless explicitly disabled) + level_zero_enabled = False if args.no_level_zero else True + + cmake_args = make_cmake_args( + c_compiler=c_compiler, + cxx_compiler=cxx_compiler, + level_zero=level_zero_enabled, + verbose=args.verbose, + ) + + cmake_args += ["-DDPCTL_GENERATE_COVERAGE=ON"] + cmake_args += ["-DDPCTL_BUILD_CAPI_TESTS=ON"] + cmake_args += [f"-DDPCTL_COVERAGE_REPORT_OUTPUT={setup_dir}"] + + if args.gtest_config: + cmake_args += [f"-DCMAKE_PREFIX_PATH={args.gtest_config}"] + + env = os.environ.copy() + if bin_llvm: - env = { - "PATH": ":".join((os.environ.get("PATH", ""), bin_llvm)), - "LLVM_TOOLS_HOME": bin_llvm, - } - env.update({k: v for k, v in os.environ.items() if k != "PATH"}) - if gtest_config: - cmake_args += ["-DCMAKE_PREFIX_PATH=" + gtest_config] - if verbose: - cmake_args += [ - "-DCMAKE_VERBOSE_MAKEFILE:BOOL=ON", - ] - subprocess.check_call(cmake_args, shell=False, cwd=setup_dir, env=env) + env["PATH"] = ":".join((env.get("PATH", ""), bin_llvm)) + env["LLVM_TOOLS_HOME"] = bin_llvm + + log_cmake_args(cmake_args, "gen_coverage") + + build_extension( + setup_dir, + env, + cmake_args, + cmake_executable=args.cmake_executable, + generator=args.generator, + build_type="Coverage", + ) + install_editable(setup_dir, env) + cmake_build_dir = ( subprocess.check_output( ["find", "_skbuild", "-name", "cmake-build"], cwd=setup_dir @@ -81,13 +193,22 @@ def run( .decode("utf-8") .strip("\n") ) - subprocess.check_call( + + cmake_build_dir = capture_cmd_output( + ["find", "_skbuild", "-name", "cmake-build"], + cwd=setup_dir, + ) + + print(f"[gen_coverage] Found CMake build dir: {cmake_build_dir}") + + run( ["cmake", "--build", ".", "--target", "llvm-cov-report"], cwd=cmake_build_dir, ) - env["LLVM_PROFILE_FILE"] = "dpctl_pytest.profraw" - subprocess.check_call( - [ + + if args.run_pytest: + env["LLVM_PROFILE_FILE"] = "dpctl_pytest.profraw" + pytest_cmd = [ "pytest", "-q", "-ra", @@ -103,147 +224,66 @@ def run( "-vv", "--ignore=dpctl/tensor/libtensor/tests", "--no-sycl-interface-test", - ], - cwd=setup_dir, - shell=False, - env=env, - ) - - def find_objects(): - import os - - objects = [] - sfx_regexp = sysconfig.get_config_var("EXT_SUFFIX").replace(".", r"\.") - regexp1 = re.compile(r"^_tensor_.*impl" + sfx_regexp) - regexp2 = re.compile(r"^^_device_queries" + sfx_regexp) - - def is_py_ext(fn): - return re.match(regexp1, fn) or re.match(regexp2, fn) - - for root, _, files in os.walk("dpctl"): - for file in files: - if not file.endswith(".so"): - continue - if is_py_ext(file) or file.find("DPCTLSyclInterface") != -1: - objects.extend(["-object", os.path.join(root, file)]) - print("Using objects: ", objects) - return objects - - objects = find_objects() - instr_profile_fn = "dpctl_pytest.profdata" - # generate instrumentation profile data - subprocess.check_call( - [ - os.path.join(bin_llvm, "llvm-profdata"), - "merge", - "-sparse", - env["LLVM_PROFILE_FILE"], - "-o", - instr_profile_fn, ] - ) - # export lcov - with open("dpctl_pytest.lcov", "w") as fh: - subprocess.check_call( + run(pytest_cmd, env=env, cwd=setup_dir) + + def find_objects(): + objects = [] + sfx_regexp = sysconfig.get_config_var("EXT_SUFFIX").replace( + ".", r"\." + ) + regexp1 = re.compile(r"^_tensor_.*impl" + sfx_regexp) + regexp2 = re.compile(r"^^_device_queries" + sfx_regexp) + + def is_py_ext(fn): + return re.match(regexp1, fn) or re.match(regexp2, fn) + + for root, _, files in os.walk("dpctl"): + for file in files: + if not file.endswith(".so"): + continue + if is_py_ext(file) or "DPCTLSyclInterface" in file: + objects.extend(["-object", os.path.join(root, file)]) + print("Using objects: ", objects) + return objects + + objects = find_objects() + instr_profile_fn = "dpctl_pytest.profdata" + + run( [ - os.path.join(bin_llvm, "llvm-cov"), - "export", - "-format=lcov", - "-ignore-filename-regex=/tmp/icpx*", - "-instr-profile=" + instr_profile_fn, + os.path.join(bin_llvm, "llvm-profdata"), + "merge", + "-sparse", + env["LLVM_PROFILE_FILE"], + "-o", + instr_profile_fn, ] - + objects, - stdout=fh, ) + with open("dpctl_pytest.lcov", "w") as fh: + subprocess.check_call( + [ + os.path.join(bin_llvm, "llvm-cov"), + "export", + "-format=lcov", + "-ignore-filename-regex=/tmp/icpx*", + f"-instr-profile={instr_profile_fn}", + ] + + objects, + cwd=setup_dir, + env=env, + stdout=fh, + ) + print("[gen_coverage] Coverage export complete: dpctl_pytest.lcov") + else: + print( + "[gen_coverage] Skipping pytest and coverage collection " + "(--skip-pytest)" + ) -if __name__ == "__main__": - import argparse + print("[gen_coverage] Done") - parser = argparse.ArgumentParser( - description="Driver to build dpctl and generate coverage" - ) - driver = parser.add_argument_group(title="Coverage driver arguments") - driver.add_argument("--c-compiler", help="Name of C compiler", default=None) - driver.add_argument( - "--cxx-compiler", help="Name of C++ compiler", default=None - ) - driver.add_argument( - "--not-oneapi", - help="Is one-API installation", - dest="oneapi", - action="store_false", - ) - driver.add_argument( - "--compiler-root", type=str, help="Path to compiler home directory" - ) - driver.add_argument( - "--no-level-zero", - help="Enable Level Zero support", - dest="level_zero", - action="store_false", - ) - driver.add_argument( - "--skip-pytest", - help="Run pytest and collect coverage", - dest="run_pytest", - action="store_false", - ) - driver.add_argument( - "--bin-llvm", help="Path to folder where llvm-cov can be found" - ) - driver.add_argument( - "--verbose", - help="Build using vebose makefile mode", - dest="verbose", - action="store_true", - ) - driver.add_argument( - "--gtest-config", - help="Path to the GTestConfig.cmake file to locate a " - + "custom GTest installation.", - ) - args = parser.parse_args() - - if args.oneapi: - args.c_compiler = "icx" - args.cxx_compiler = "icpx" - args.compiler_root = None - icx_path = subprocess.check_output(["which", "icx"]) - bin_dir = os.path.dirname(icx_path) - compiler_dir = os.path.join(bin_dir.decode("utf-8"), "compiler") - if os.path.exists(compiler_dir): - args.bin_llvm = os.path.join(bin_dir.decode("utf-8"), "compiler") - else: - bin_dir = os.path.dirname(bin_dir) - args.bin_llvm = os.path.join(bin_dir.decode("utf-8"), "bin-llvm") - assert os.path.exists(args.bin_llvm) - else: - args_to_validate = [ - "c_compiler", - "cxx_compiler", - "compiler_root", - "bin_llvm", - ] - for p in args_to_validate: - arg = getattr(args, p, None) - if not isinstance(arg, str): - opt_name = p.replace("_", "-") - raise RuntimeError( - f"Option {opt_name} must be provided is " - "using non-default DPC++ layout" - ) - if not os.path.exists(arg): - raise RuntimeError(f"Path {arg} must exist") - run( - use_oneapi=args.oneapi, - c_compiler=args.c_compiler, - cxx_compiler=args.cxx_compiler, - level_zero=args.level_zero, - compiler_root=args.compiler_root, - run_pytest=args.run_pytest, - bin_llvm=args.bin_llvm, - gtest_config=args.gtest_config, - verbose=args.verbose, - ) +if __name__ == "__main__": + main() diff --git a/scripts/gen_docs.py b/scripts/gen_docs.py index b5cf1b0602..2b72c033d5 100644 --- a/scripts/gen_docs.py +++ b/scripts/gen_docs.py @@ -14,175 +14,165 @@ # See the License for the specific language governing permissions and # limitations under the License. +import argparse import os import subprocess import sys - -def run( - use_oneapi=True, - c_compiler=None, - cxx_compiler=None, - level_zero=True, - compiler_root=None, - bin_llvm=None, - doxyrest_dir=None, - verbose=False, - cmake_opts="", -): - IS_LIN = False - - if "linux" in sys.platform: - IS_LIN = True - elif sys.platform in ["win32", "cygwin"]: - pass - else: - assert False, sys.platform + " not supported" - - if not IS_LIN: - raise RuntimeError( - "This scripts only supports coverage collection on Linux" - ) - setup_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) - cmake_args = [ - sys.executable, - "setup.py", - "develop", - "--build-type=Release", - "--generator=Ninja", - "--", - "-DCMAKE_C_COMPILER:PATH=" + c_compiler, - "-DCMAKE_CXX_COMPILER:PATH=" + cxx_compiler, - "-DDPCTL_ENABLE_L0_PROGRAM_CREATION=" + ("ON" if level_zero else "OFF"), - "-DDPCTL_GENERATE_DOCS=ON", - ] - - if verbose: - cmake_args.append("-DCMAKE_VERBOSE_MAKEFILE=ON") - - if doxyrest_dir: - cmake_args.append("-DDPCTL_ENABLE_DOXYREST=ON") - cmake_args.append("-DDoxyrest_DIR=" + doxyrest_dir) - - if cmake_opts: - cmake_args += cmake_opts.split() - - env = dict() - if bin_llvm: - env = { - "PATH": ":".join((os.environ.get("PATH", ""), bin_llvm)), - } - env.update({k: v for k, v in os.environ.items() if k != "PATH"}) - # Install dpctl package - subprocess.check_call(cmake_args, shell=False, cwd=setup_dir, env=env) - # Get the path for the build directory - build_dir = ( - subprocess.check_output( - ["find", "_skbuild", "-name", "cmake-build"], - cwd=setup_dir, - ) - .decode("utf-8") - .strip("\n") - ) - # Generate docs - subprocess.check_call( - ["cmake", "--build", ".", "--target", "Sphinx"], cwd=build_dir - ) - generated_doc_dir = ( - subprocess.check_output( - ["find", "_skbuild", "-name", "index.html"], cwd=setup_dir - ) - .decode("utf-8") - .strip("\n") - ) - print("Generated documentation placed under ", generated_doc_dir) +from _build_helper import ( + build_extension, + capture_cmd_output, + clean_build_dir, + err, + install_editable, + log_cmake_args, + make_cmake_args, + resolve_compilers, + run, +) -if __name__ == "__main__": - import argparse +def parse_args(): + p = argparse.ArgumentParser(description="Build dpctl and generate coverage") - parser = argparse.ArgumentParser( - description="Driver to build dpctl and generate coverage" + p.add_argument( + "--c-compiler", default=None, help="Path or name of C compiler" ) - driver = parser.add_argument_group(title="Coverage driver arguments") - driver.add_argument("--c-compiler", help="Name of C compiler", default=None) - driver.add_argument( - "--cxx-compiler", help="Name of C++ compiler", default=None + p.add_argument( + "--cxx-compiler", default=None, help="Path or name of C++ compiler" ) - driver.add_argument( - "--not-oneapi", - help="Is one-API installation", + p.add_argument( + "--compiler-root", + type=str, + default=None, + help="Path to compiler installation root", + ) + p.add_argument( + "--oneapi", dest="oneapi", - action="store_false", + action="store_true", + help="Use default oneAPI compiler layout", ) - driver.add_argument( - "--compiler-root", type=str, help="Path to compiler home directory" + + p.add_argument( + "--verbose", + dest="verbose", + action="store_true", + help="Enable verbose makefile output", ) - driver.add_argument( + + p.add_argument( "--no-level-zero", - help="Enable Level Zero support", - dest="level_zero", - action="store_false", + dest="no_level_zero", + action="store_true", + default=False, + help="Disable Level Zero backend (deprecated: use --target-level-zero " + "OFF)", + ) + + p.add_argument( + "--generator", type=str, default="Ninja", help="CMake generator" ) - driver.add_argument( - "--bin-llvm", help="Path to folder where llvm-cov can be found" + p.add_argument( + "--cmake-executable", + type=str, + default=None, + help="Path to CMake executable used by build", ) - driver.add_argument( + + p.add_argument( + "--cmake-opts", + type=str, + default="", + help="Additional options to pass directly to CMake", + ) + + p.add_argument( "--doxyrest-root", + type=str, help=( "Path to Doxyrest installation to use to generate Sphinx docs" + "for libsyclinterface" ), ) - driver.add_argument( - "--verbose", - help="Build using vebose makefile mode", - dest="verbose", + + p.add_argument( + "--clean", action="store_true", + help="Remove build dir before rebuild (default: False)", ) - driver.add_argument( - "--cmake-opts", - help="Options to pass through to cmake", - dest="cmake_opts", - default="", - type=str, + + return p.parse_args() + + +def main(): + is_linux = "linux" in sys.platform + if not is_linux: + err(f"{sys.platform} not supported", "gen_docs") + args = parse_args() + setup_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + c_compiler, cxx_compiler = resolve_compilers( + args.oneapi, + args.c_compiler, + args.cxx_compiler, + args.compiler_root, ) - args = parser.parse_args() - - if args.oneapi: - args.c_compiler = "icx" - args.cxx_compiler = "icpx" - args.compiler_root = None - icx_path = subprocess.check_output(["which", "icx"]) - bin_dir = os.path.dirname(icx_path) - args.bin_llvm = os.path.join(bin_dir.decode("utf-8"), "compiler") - else: - args_to_validate = [ - "c_compiler", - "cxx_compiler", - "compiler_root", - "bin_llvm", - ] - for p in args_to_validate: - arg = getattr(args, p, None) - if not isinstance(arg, str): - opt_name = p.replace("_", "-") - raise RuntimeError( - f"Option {opt_name} must be provided is " - "using non-default DPC++ layout" - ) - if not os.path.exists(arg): - raise RuntimeError(f"Path {arg} must exist") + if args.clean: + clean_build_dir(setup_dir) - run( - use_oneapi=args.oneapi, - c_compiler=args.c_compiler, - cxx_compiler=args.cxx_compiler, - level_zero=args.level_zero, - compiler_root=args.compiler_root, - bin_llvm=args.bin_llvm, - doxyrest_dir=args.doxyrest_root, + # Level Zero state (on unless explicitly disabled) + level_zero_enabled = False if args.no_level_zero else True + + cmake_args = make_cmake_args( + c_compiler=c_compiler, + cxx_compiler=cxx_compiler, + level_zero=level_zero_enabled, verbose=args.verbose, - cmake_opts=args.cmake_opts, ) + + cmake_args += ["-DDPCTL_GENERATE_DOCS=ON"] + + if args.doxyrest_root: + cmake_args += ["-DDPCTL_ENABLE_DOXYREST=ON"] + cmake_args += [f"-DDoxyrest_DIR={args.doxyrest_root}"] + + log_cmake_args(cmake_args, "gen_docs") + + env = os.environ.copy() + + build_extension( + setup_dir, + env, + cmake_args, + cmake_executable=args.cmake_executable, + generator=args.generator, + build_type="Release", + ) + install_editable(setup_dir, env) + cmake_build_dir = capture_cmd_output( + ["find", "_skbuild", "-name", "cmake-build"], cwd=setup_dir + ) + + print(f"[gen_docs] Found CMake build dir: {cmake_build_dir}") + + run( + ["cmake", "--build", ".", "--target", "Sphinx"], + cwd=cmake_build_dir, + ) + + generated_doc_dir = ( + subprocess.check_output( + ["find", "_skbuild", "-name", "index.html"], cwd=setup_dir + ) + .decode("utf-8") + .strip("\n") + ) + print("Generated documentation placed under ", generated_doc_dir) + + print("[gen_docs] Done") + + +if __name__ == "__main__": + main()