This repository was archived by the owner on Apr 6, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
Add support for building CPU-only kernels #284
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
ee21fc2
Add support for building CPU-only kernels
danieldk 7e0d0b3
Test CPU kernel
danieldk 591fcf5
Add CPU build variants to metadata/docs
danieldk a357421
Try to fix Dockerfile
danieldk ae54ec5
Fix script path
danieldk e396427
Docker test fixes
danieldk 4dcfd02
Fixes from @MekkCyber
danieldk File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| set({{kernel_name}}_SRC | ||
| {{ sources }} | ||
| ) | ||
|
|
||
| {% if includes %} | ||
| # TODO: check if CLion support this: | ||
| # https://youtrack.jetbrains.com/issue/CPP-16510/CLion-does-not-handle-per-file-include-directories | ||
| set_source_files_properties( | ||
| {{'${' + kernel_name + '_SRC}'}} | ||
| PROPERTIES INCLUDE_DIRECTORIES "{{ includes }}") | ||
| {% endif %} | ||
|
|
||
| {% if cxx_flags %} | ||
| foreach(_KERNEL_SRC {{'${' + kernel_name + '_SRC}'}}) | ||
| set_property( | ||
| SOURCE ${_KERNEL_SRC} | ||
| APPEND PROPERTY | ||
| COMPILE_OPTIONS "$<$<COMPILE_LANGUAGE:CXX>:{{ cxx_flags }}>" | ||
| ) | ||
| endforeach() | ||
| {% endif %} | ||
|
|
||
| # Add C++ sources to main source list | ||
| list(APPEND SRC {{'"${' + kernel_name + '_SRC}"'}}) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| cmake_minimum_required(VERSION 3.26) | ||
| project({{name}} LANGUAGES CXX) | ||
|
|
||
| set(CMAKE_OSX_DEPLOYMENT_TARGET "15.0" CACHE STRING "Minimum macOS deployment version") | ||
|
|
||
| install(CODE "set(CMAKE_INSTALL_LOCAL_ONLY TRUE)" ALL_COMPONENTS) | ||
|
|
||
| include(FetchContent) | ||
| file(MAKE_DIRECTORY ${FETCHCONTENT_BASE_DIR}) # Ensure the directory exists | ||
| message(STATUS "FetchContent base directory: ${FETCHCONTENT_BASE_DIR}") | ||
|
|
||
| include(${CMAKE_CURRENT_LIST_DIR}/cmake/utils.cmake) | ||
|
|
||
| if(DEFINED Python3_EXECUTABLE) | ||
| # Allow passing through the interpreter (e.g. from setup.py). | ||
| find_package(Python3 COMPONENTS Development Development.SABIModule Interpreter) | ||
| if (NOT Python3_FOUND) | ||
| message(FATAL_ERROR "Unable to find python matching: ${EXECUTABLE}.") | ||
| endif() | ||
| else() | ||
| find_package(Python3 REQUIRED COMPONENTS Development Development.SABIModule Interpreter) | ||
| endif() | ||
|
|
||
| append_cmake_prefix_path("torch" "torch.utils.cmake_prefix_path") | ||
|
|
||
| find_package(Torch REQUIRED) | ||
|
|
||
| add_compile_definitions(CPU_KERNEL) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,121 @@ | ||
| import logging | ||
| import os | ||
| from shutil import which, move | ||
| import subprocess | ||
| import sys | ||
| from pathlib import Path | ||
|
|
||
| from setuptools import Extension, find_packages, setup | ||
| from setuptools.command.build_ext import build_ext | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def is_sccache_available() -> bool: | ||
| return which("sccache") is not None | ||
|
|
||
|
|
||
| def is_ccache_available() -> bool: | ||
| return which("ccache") is not None | ||
|
|
||
|
|
||
| def is_ninja_available() -> bool: | ||
| return which("ninja") is not None | ||
|
|
||
|
|
||
| class CMakeExtension(Extension): | ||
| def __init__(self, name: str, sourcedir: str = "") -> None: | ||
| super().__init__(name, sources=[], py_limited_api=True) | ||
| self.sourcedir = os.fspath(Path(sourcedir).resolve()) | ||
|
|
||
|
|
||
| class CMakeBuild(build_ext): | ||
| def build_extension(self, ext: CMakeExtension) -> None: | ||
| ext_fullpath = Path.cwd() / self.get_ext_fullpath(ext.name) | ||
| extdir = ext_fullpath.parent.resolve() | ||
|
|
||
| debug = int(os.environ.get("DEBUG", 0)) if self.debug is None else self.debug | ||
| cfg = "Debug" if debug else "Release" | ||
|
|
||
| cmake_generator = os.environ.get("CMAKE_GENERATOR", "") | ||
|
|
||
| # Set Python3_EXECUTABLE instead if you use PYBIND11_FINDPYTHON | ||
| # EXAMPLE_VERSION_INFO shows you how to pass a value into the C++ code | ||
| # from Python. | ||
| cmake_args = [ | ||
| f"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY={extdir}{os.sep}", | ||
| f"-DPython3_EXECUTABLE={sys.executable}", | ||
| f"-DCMAKE_BUILD_TYPE={cfg}", # not used on MSVC, but no harm | ||
| ] | ||
| build_args = [] | ||
| if "CMAKE_ARGS" in os.environ: | ||
| cmake_args += [item for item in os.environ["CMAKE_ARGS"].split(" ") if item] | ||
|
|
||
| if not cmake_generator or cmake_generator == "Ninja": | ||
| try: | ||
| import ninja | ||
|
|
||
| ninja_executable_path = Path(ninja.BIN_DIR) / "ninja" | ||
| cmake_args += [ | ||
| "-GNinja", | ||
| f"-DCMAKE_MAKE_PROGRAM:FILEPATH={ninja_executable_path}", | ||
| ] | ||
| except ImportError: | ||
| pass | ||
|
|
||
| if is_sccache_available(): | ||
| cmake_args += [ | ||
| "-DCMAKE_C_COMPILER_LAUNCHER=sccache", | ||
| "-DCMAKE_CXX_COMPILER_LAUNCHER=sccache", | ||
| "-DCMAKE_HIP_COMPILER_LAUNCHER=sccache", | ||
| "-DCMAKE_OBJC_COMPILER_LAUNCHER=sccache", | ||
| "-DCMAKE_OBJCXX_COMPILER_LAUNCHER=sccache", | ||
| ] | ||
| elif is_ccache_available(): | ||
| cmake_args += [ | ||
| "-DCMAKE_C_COMPILER_LAUNCHER=ccache", | ||
| "-DCMAKE_CXX_COMPILER_LAUNCHER=ccache", | ||
| "-DCMAKE_HIP_COMPILER_LAUNCHER=ccache", | ||
| "-DCMAKE_OBJC_COMPILER_LAUNCHER=ccache", | ||
| "-DCMAKE_OBJCXX_COMPILER_LAUNCHER=ccache", | ||
| ] | ||
|
|
||
| num_jobs = os.getenv("MAX_JOBS", None) | ||
| if num_jobs is not None: | ||
| num_jobs = int(num_jobs) | ||
| logger.info("Using MAX_JOBS=%d as the number of jobs.", num_jobs) | ||
| else: | ||
| try: | ||
| # os.sched_getaffinity() isn't universally available, so fall | ||
| # back to os.cpu_count() if we get an error here. | ||
| num_jobs = len(os.sched_getaffinity(0)) | ||
| except AttributeError: | ||
| num_jobs = os.cpu_count() | ||
|
|
||
| build_temp = Path(self.build_temp) / ext.name | ||
| if not build_temp.exists(): | ||
| build_temp.mkdir(parents=True) | ||
|
|
||
| subprocess.run( | ||
| ["cmake", ext.sourcedir, *cmake_args], cwd=build_temp, check=True | ||
| ) | ||
| subprocess.run( | ||
| ["cmake", "--build", ".", *build_args], cwd=build_temp, check=True | ||
| ) | ||
|
|
||
|
|
||
| setup( | ||
| name="{{ name }}", | ||
| # The version is just a stub, it's not used by the final build artefact. | ||
| version="0.1.0", | ||
| ext_modules=[CMakeExtension("{{ name }}.{{ ops_name }}")], | ||
| cmdclass={"build_ext": CMakeBuild}, | ||
| packages=find_packages(where="torch-ext", include=["{{ name }}*"]), | ||
| package_dir={"": "torch-ext"}, | ||
| {% if data_globs %} | ||
| package_data={"{{ name }}": [ {{ data_globs }} ]}, | ||
| {% endif %} | ||
| zip_safe=False, | ||
| install_requires=["torch"], | ||
| python_requires=">=3.9", | ||
| ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| set(TORCH_{{name}}_SRC | ||
| {{ src|join(' ') }} | ||
| ) | ||
|
|
||
| {% if includes %} | ||
| # TODO: check if CLion support this: | ||
| # https://youtrack.jetbrains.com/issue/CPP-16510/CLion-does-not-handle-per-file-include-directories | ||
| set_source_files_properties( | ||
| {{'${TORCH_' + name + '_SRC}'}} | ||
| PROPERTIES INCLUDE_DIRECTORIES "{{ includes }}") | ||
| {% endif %} | ||
|
|
||
| list(APPEND SRC {{'"${TORCH_' + name + '_SRC}"'}}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| define_gpu_extension_target( | ||
| {{ ops_name }} | ||
| DESTINATION {{ ops_name }} | ||
| LANGUAGE ${GPU_LANG} | ||
| SOURCES ${SRC} | ||
| COMPILE_FLAGS ${GPU_FLAGS} | ||
| ARCHITECTURES ${GPU_ARCHES} | ||
| USE_SABI 3 | ||
| WITH_SOABI) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why do we set the flags for each source file separately ?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
IIRC we have to set it on the whole target otherwise, which would result in applying the flags for other kernels as well.