From 34eebdca254e768091eeaf1f6ac6955fac657cfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Fri, 22 May 2026 12:32:23 +0000 Subject: [PATCH 1/6] kernel-builder: add `stable-abi` option This change adds an option `stable-abi` to `build.toml`. When setting ```toml [torch] stable-abi = "2.11" ``` The extension will be built targeting the Torch 2.11 stable ABI. In this case, the variant naming pattern will also change from `torch` to `torch-stable-abi`. --- kernel-builder/src/main.rs | 4 +- .../templates/torch/build-variants.cmake | 60 ++++++++++++------- .../pyproject/templates/torch/preamble.cmake | 28 +++++++-- .../pyproject/templates/torch/registration.h | 9 +++ kernel-builder/src/pyproject/torch/mod.rs | 1 + kernel-builder/src/upload.rs | 3 + kernel-builder/src/util.rs | 29 +++++---- kernels-data/src/config/mod.rs | 3 + kernels-data/src/config/v3.rs | 1 + kernels-data/src/config/v4.rs | 6 +- kernels-data/src/version.rs | 10 ++++ 11 files changed, 115 insertions(+), 39 deletions(-) diff --git a/kernel-builder/src/main.rs b/kernel-builder/src/main.rs index 73f31f7ff..19a8bbf13 100644 --- a/kernel-builder/src/main.rs +++ b/kernel-builder/src/main.rs @@ -43,6 +43,8 @@ use util::{check_or_infer_kernel_dir, parse_and_validate}; mod validate_builds; use validate_builds::check_builds; +use crate::util::parse_and_validate_compat; + #[derive(Args, Debug)] struct NixArgs { /// Maximum number of parallel Nix build jobs. @@ -417,7 +419,7 @@ fn check_config(kernel_dir: Option) -> Result<()> { fn update_build(kernel_dir: Option) -> Result<()> { let kernel_dir = check_or_infer_kernel_dir(kernel_dir)?; - let build_compat: BuildCompat = parse_and_validate(&kernel_dir)?; + let build_compat: BuildCompat = parse_and_validate_compat(&kernel_dir)?; if matches!(build_compat, BuildCompat::V4(_)) { return Ok(()); diff --git a/kernel-builder/src/pyproject/templates/torch/build-variants.cmake b/kernel-builder/src/pyproject/templates/torch/build-variants.cmake index 2acaed451..24f6718c7 100644 --- a/kernel-builder/src/pyproject/templates/torch/build-variants.cmake +++ b/kernel-builder/src/pyproject/templates/torch/build-variants.cmake @@ -1,30 +1,51 @@ # Generate a standardized build variant name following the pattern: -# torch-[cxx11-]-- +# torch--- +# or, when compiled against the Torch stable ABI: +# torch-stable-abi--- # # Arguments: # OUT_BUILD_NAME - Output variable name -# TORCH_VERSION - PyTorch version (e.g., "2.7.1") +# TORCH_VERSION - PyTorch version (e.g., "2.7.1"); ignored when TORCH_STABLE_ABI is set # COMPUTE_FRAMEWORK - One of: cuda, rocm, metal, xpu, cpu # COMPUTE_VERSION - Version of compute framework (e.g., "12.4" for CUDA, "6.0" for ROCm) # Optional for CPU-only builds (pass empty string or omit) -# Example output: torch271-cxx11-cu124-x86_64-linux (Linux) -# torch271-cu124-x86_64-windows (Windows) -# torch271-metal-aarch64-darwin (macOS) +# Optional keyword arguments: +# TORCH_STABLE_ABI - Stable ABI version the extension was compiled against (e.g., "2.11"); +# when set, TORCH_VERSION is ignored and the prefix becomes +# torch-stable-abi (e.g., "2.11" -> "torch-stable-abi211") +# Example output: torch27-cu124-x86_64-linux (Linux) +# torch27-cu124-x86_64-windows (Windows) +# torch27-metal-aarch64-darwin (macOS) +# torch-stable-abi211-cu124-x86_64-linux (Linux, stable ABI) # function(generate_build_name OUT_BUILD_NAME TORCH_VERSION COMPUTE_FRAMEWORK COMPUTE_VERSION) - # Flatten version by removing dots and padding to 2 components - string(REPLACE "." ";" VERSION_LIST "${TORCH_VERSION}") - list(LENGTH VERSION_LIST VERSION_COMPONENTS) + cmake_parse_arguments(ARG "" "TORCH_STABLE_ABI" "" ${ARGN}) + + if(ARG_TORCH_STABLE_ABI) + # Flatten the stable ABI version (e.g., "2.11" -> "211") and ignore TORCH_VERSION + string(REPLACE "." ";" VERSION_LIST "${ARG_TORCH_STABLE_ABI}") + list(LENGTH VERSION_LIST VERSION_COMPONENTS) + if(VERSION_COMPONENTS LESS 2) + list(APPEND VERSION_LIST "0") + endif() + list(GET VERSION_LIST 0 MAJOR) + list(GET VERSION_LIST 1 MINOR) + set(TORCH_PREFIX "torch-stable-abi${MAJOR}${MINOR}") + else() + # Flatten version by removing dots and padding to 2 components + string(REPLACE "." ";" VERSION_LIST "${TORCH_VERSION}") + list(LENGTH VERSION_LIST VERSION_COMPONENTS) - # Pad to at least 2 components - if(VERSION_COMPONENTS LESS 2) - list(APPEND VERSION_LIST "0") - endif() + # Pad to at least 2 components + if(VERSION_COMPONENTS LESS 2) + list(APPEND VERSION_LIST "0") + endif() - # Take first 2 components and join without dots - list(GET VERSION_LIST 0 MAJOR) - list(GET VERSION_LIST 1 MINOR) - set(FLATTENED_TORCH "${MAJOR}${MINOR}") + # Take first 2 components and join without dots + list(GET VERSION_LIST 0 MAJOR) + list(GET VERSION_LIST 1 MINOR) + set(TORCH_PREFIX "torch${MAJOR}${MINOR}") + endif() # Generate compute string if(COMPUTE_FRAMEWORK STREQUAL "cuda") @@ -96,12 +117,7 @@ function(generate_build_name OUT_BUILD_NAME TORCH_VERSION COMPUTE_FRAMEWORK COMP set(ARCH_OS_STRING "${CPU_ARCH}-${OS_NAME}") # Assemble the final build name - # For Linux, include cxx11 ABI indicator for compatibility - if(ARCH_OS_STRING MATCHES "-linux$") - set(BUILD_NAME "torch${FLATTENED_TORCH}-cxx11-${COMPUTE_STRING}-${ARCH_OS_STRING}") - else() - set(BUILD_NAME "torch${FLATTENED_TORCH}-${COMPUTE_STRING}-${ARCH_OS_STRING}") - endif() + set(BUILD_NAME "${TORCH_PREFIX}-${COMPUTE_STRING}-${ARCH_OS_STRING}") set(${OUT_BUILD_NAME} "${BUILD_NAME}" PARENT_SCOPE) message(STATUS "Generated build name: ${BUILD_NAME}") diff --git a/kernel-builder/src/pyproject/templates/torch/preamble.cmake b/kernel-builder/src/pyproject/templates/torch/preamble.cmake index 69b578200..0620a2e00 100644 --- a/kernel-builder/src/pyproject/templates/torch/preamble.cmake +++ b/kernel-builder/src/pyproject/templates/torch/preamble.cmake @@ -65,6 +65,21 @@ if (TORCH_VERSION VERSION_GREATER {{ torch_maxver }}) endif() {% endif %} +{% if stable_abi %} +if (TORCH_VERSION VERSION_LESS {{ stable_abi }}) + message(FATAL_ERROR "Torch version ${TORCH_VERSION} is less than the stable ABI " + "version {{ stable_abi }}. Cannot build with stable ABI targeting a newer Torch.") +endif() + +# From the Torch docs: TORCH_TARGET_VERSION (((0ULL + major) << 56) | ((0ULL + minor) << 48)) +string(REPLACE "." ";" _STABLE_ABI_VERSION_LIST "{{ stable_abi }}") +list(GET _STABLE_ABI_VERSION_LIST 0 _STABLE_ABI_MAJOR) +list(GET _STABLE_ABI_VERSION_LIST 1 _STABLE_ABI_MINOR) +math(EXPR _STABLE_ABI_HEX "(${_STABLE_ABI_MAJOR} << 56) | (${_STABLE_ABI_MINOR} << 48)" OUTPUT_FORMAT HEXADECIMAL) + +add_compile_definitions(-DTORCH_TARGET_VERSION=${_STABLE_ABI_HEX}) +{% endif %} + option(BUILD_ALL_SUPPORTED_ARCHS "Build all supported architectures" off) if(DEFINED CMAKE_CUDA_COMPILER_VERSION AND @@ -195,17 +210,20 @@ set(SRC "") include(${CMAKE_CURRENT_LIST_DIR}/cmake/build-variants.cmake) # Generate build variant name. +{% if stable_abi %} +set(_STABLE_ABI_ARG TORCH_STABLE_ABI "{{ stable_abi }}") +{% endif %} if(GPU_LANG STREQUAL "CUDA") - generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "cuda" "${CUDA_VERSION}") + generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "cuda" "${CUDA_VERSION}" ${_STABLE_ABI_ARG}) elseif(GPU_LANG STREQUAL "HIP") run_python(ROCM_VERSION "import torch.version; print(torch.version.hip.split('.')[0] + '.' + torch.version.hip.split('.')[1])" "Failed to get ROCm version") - generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "rocm" "${ROCM_VERSION}") + generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "rocm" "${ROCM_VERSION}" ${_STABLE_ABI_ARG}) elseif(GPU_LANG STREQUAL "SYCL") - generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "xpu" "${DPCPP_VERSION}") + generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "xpu" "${DPCPP_VERSION}" ${_STABLE_ABI_ARG}) elseif(GPU_LANG STREQUAL "METAL") - generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "metal" "") + generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "metal" "" ${_STABLE_ABI_ARG}) elseif(GPU_LANG STREQUAL "CPU") - generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "cpu" "") + generate_build_name(BUILD_VARIANT_NAME "${TORCH_VERSION}" "cpu" "" ${_STABLE_ABI_ARG}) else() message(FATAL_ERROR "Cannot generate build name for unknown GPU_LANG: ${GPU_LANG}") endif() diff --git a/kernel-builder/src/pyproject/templates/torch/registration.h b/kernel-builder/src/pyproject/templates/torch/registration.h index 19a82cca9..096da4beb 100644 --- a/kernel-builder/src/pyproject/templates/torch/registration.h +++ b/kernel-builder/src/pyproject/templates/torch/registration.h @@ -15,11 +15,20 @@ // could be a macro instead of a literal token. #define TORCH_LIBRARY_EXPAND(NAME, MODULE) TORCH_LIBRARY(NAME, MODULE) +// A version of the STABLE_TORCH_LIBRARY macro that expands the NAME, i.e. so NAME +// could be a macro instead of a literal token. +#define STABLE_TORCH_LIBRARY_EXPAND(NAME, MODULE) STABLE_TORCH_LIBRARY(NAME, MODULE) + // A version of the TORCH_LIBRARY_IMPL macro that expands the NAME, i.e. so NAME // could be a macro instead of a literal token. #define TORCH_LIBRARY_IMPL_EXPAND(NAME, DEVICE, MODULE) \ TORCH_LIBRARY_IMPL(NAME, DEVICE, MODULE) +// A version of the STABLE_TORCH_LIBRARY_IMPL macro that expands the NAME, i.e. so NAME +// could be a macro instead of a literal token. +#define STABLE_TORCH_LIBRARY_IMPL_EXPAND(NAME, DEVICE, MODULE) \ + STABLE_TORCH_LIBRARY_IMPL(NAME, DEVICE, MODULE) + // REGISTER_EXTENSION allows the shared library to be loaded and initialized // via python's import statement. #define REGISTER_EXTENSION(NAME) \ diff --git a/kernel-builder/src/pyproject/torch/mod.rs b/kernel-builder/src/pyproject/torch/mod.rs index 4b7882d5b..dae4265ac 100644 --- a/kernel-builder/src/pyproject/torch/mod.rs +++ b/kernel-builder/src/pyproject/torch/mod.rs @@ -206,6 +206,7 @@ fn render_preamble( cuda_maxver => cuda_maxver.map(|v| v.to_string()), torch_minver => torch.minver.as_ref().map(|v| v.to_string()), torch_maxver => torch.maxver.as_ref().map(|v| v.to_string()), + stable_abi => torch.stable_abi.as_ref().map(|v| v.to_string()), }, &mut *write, ) diff --git a/kernel-builder/src/upload.rs b/kernel-builder/src/upload.rs index 8d7c639f0..9a6f5edd9 100644 --- a/kernel-builder/src/upload.rs +++ b/kernel-builder/src/upload.rs @@ -737,10 +737,13 @@ mod tests { name = "test-kernel" license = "Apache-2.0" backends = ["cuda"] +version = 1 [general.hub] repo-id = "test/kernel" branch = "custom-branch" + +[torch] "#, ) .unwrap(); diff --git a/kernel-builder/src/util.rs b/kernel-builder/src/util.rs index 7049a19c8..d61048200 100644 --- a/kernel-builder/src/util.rs +++ b/kernel-builder/src/util.rs @@ -5,16 +5,11 @@ use std::path::{Path, PathBuf}; use eyre::{bail, ensure, Context, Result}; -use kernels_data::config::{Build, BuildCompat}; +use kernels_data::config::{Build, BuildCompat, CurrentConfig}; pub(crate) fn parse_build(kernel_dir: impl AsRef) -> Result { let build_compat = parse_and_validate(kernel_dir)?; - - let build: Build = build_compat - .try_into() - .context("Cannot update build configuration")?; - - Ok(build) + Ok(build_compat.into()) } pub(crate) fn check_or_infer_kernel_dir(kernel_dir: Option) -> Result { @@ -49,7 +44,21 @@ pub(crate) fn check_or_infer_target_dir( } } -pub(crate) fn parse_and_validate(kernel_dir: impl AsRef) -> Result { +pub(crate) fn parse_and_validate(kernel_dir: impl AsRef) -> Result { + let build_toml = kernel_dir.as_ref().join("build.toml"); + let mut toml_data = String::new(); + File::open(&build_toml) + .wrap_err_with(|| format!("Cannot open {} for reading", build_toml.to_string_lossy()))? + .read_to_string(&mut toml_data) + .wrap_err_with(|| format!("Cannot read from {}", build_toml.to_string_lossy()))?; + + let build: CurrentConfig = toml::from_str(&toml_data) + .wrap_err_with(|| format!("Cannot parse TOML in {}", build_toml.to_string_lossy()))?; + + Ok(build) +} + +pub(crate) fn parse_and_validate_compat(kernel_dir: impl AsRef) -> Result { let build_toml = kernel_dir.as_ref().join("build.toml"); let mut toml_data = String::new(); File::open(&build_toml) @@ -57,10 +66,10 @@ pub(crate) fn parse_and_validate(kernel_dir: impl AsRef) -> Result, @@ -159,6 +161,7 @@ pub struct Torch { pub maxver: Option, pub pyext: Option>, pub src: Vec, + pub stable_abi: Option, } fn data_extensions(py_ext: Option<&[String]>) -> Option> { diff --git a/kernels-data/src/config/v3.rs b/kernels-data/src/config/v3.rs index f12a3dacb..884377acb 100644 --- a/kernels-data/src/config/v3.rs +++ b/kernels-data/src/config/v3.rs @@ -248,6 +248,7 @@ impl From for super::Torch { maxver: torch.maxver, pyext: torch.pyext, src: torch.src, + stable_abi: None, } } } diff --git a/kernels-data/src/config/v4.rs b/kernels-data/src/config/v4.rs index 14386b354..519b1f04b 100644 --- a/kernels-data/src/config/v4.rs +++ b/kernels-data/src/config/v4.rs @@ -78,7 +78,7 @@ pub struct Hub { } #[derive(Debug, Deserialize, Clone, Serialize)] -#[serde(deny_unknown_fields)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] pub struct Torch { pub include: Option>, pub minver: Option, @@ -87,6 +87,8 @@ pub struct Torch { #[serde(default)] pub src: Vec, + + pub stable_abi: Option, } #[derive(Debug, Deserialize, Clone, Serialize)] @@ -247,6 +249,7 @@ impl From for super::Torch { maxver: torch.maxver, pyext: torch.pyext, src: torch.src, + stable_abi: torch.stable_abi, } } } @@ -441,6 +444,7 @@ impl From for Torch { maxver: torch.maxver, pyext: torch.pyext, src: torch.src, + stable_abi: torch.stable_abi, } } } diff --git a/kernels-data/src/version.rs b/kernels-data/src/version.rs index fb69bedce..e3ccac7f3 100644 --- a/kernels-data/src/version.rs +++ b/kernels-data/src/version.rs @@ -1,3 +1,4 @@ +use std::ops::Deref; use std::{fmt::Display, str::FromStr}; use eyre::{Context, ensure}; @@ -36,6 +37,15 @@ impl Display for Version { } } +impl Deref for Version { + type Target = [usize]; + + #[inline] + fn deref(&self) -> &[usize] { + &self.0 + } +} + impl From> for Version { fn from(value: Vec) -> Self { // Remove trailing zeros for normalization. From 7d91e09dcdc391eb3313302cf3db2b84dcefbfe6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Fri, 22 May 2026 12:41:00 +0000 Subject: [PATCH 2/6] nix-builder: wire up torch-stable-abi variants Wire up the `torch-stable-abi` variant naming. For a given ABI version, we build with the newest Torch version. --- nix-builder/lib/build.nix | 82 ++++++++++++++++++++++------ nix-builder/lib/kernel-config.nix | 6 ++ nix-builder/lib/variants/default.nix | 6 +- nix-builder/lib/variants/torch.nix | 22 ++++++-- nix-builder/lib/variants/tvm-ffi.nix | 4 +- 5 files changed, 94 insertions(+), 26 deletions(-) diff --git a/nix-builder/lib/build.nix b/nix-builder/lib/build.nix index 2c4b9bfc1..9c7d67788 100644 --- a/nix-builder/lib/build.nix +++ b/nix-builder/lib/build.nix @@ -22,29 +22,77 @@ rec { mkSourceSet = import ./source-set.nix { inherit lib; }; # Filter buildsets that are applicable to a given kernel build config. + # + # Filtering consists of two steps: + # + # 1. Filter out sets that do not correspond to the given constraints + # (e.g. CUDA version, Pytorch version). + # 2. If the kernel config uses the Torch stable ABI, we only need a + # build set for the latest Torch for a given backend + backend version + # combination. filterApplicableBuildSets = kernelConfig: buildSets: let - minCuda = kernelConfig.toml.general.cuda.minver or "11.8"; - maxCuda = kernelConfig.toml.general.cuda.maxver or "99.9"; - minTorch = kernelConfig.toml.torch.minver or "2.0"; - maxTorch = kernelConfig.toml.torch.maxver or "99.9"; - versionBetween = - minver: maxver: ver: - builtins.compareVersions ver minver >= 0 && builtins.compareVersions ver maxver <= 0; - supportedBuildSet = - buildSet: + # Step 1: build sets within the given bounds. + buildSetsWithinBounds = let - backendSupported = kernelConfig.backends.${buildSet.buildConfig.backend}; - frameworkSupported = !kernelConfig.isTvmFfi || (buildSet.buildConfig ? tvmFfiVersion); - cudaVersionSupported = - buildSet.buildConfig.backend != "cuda" - || versionBetween minCuda maxCuda buildSet.buildConfig.cudaVersion; - torchVersionSupported = versionBetween minTorch maxTorch buildSet.buildConfig.torchVersion; + minCuda = kernelConfig.toml.general.cuda.minver or "11.8"; + maxCuda = kernelConfig.toml.general.cuda.maxver or "99.9"; + minTorch = kernelConfig.toml.torch.minver or "2.0"; + maxTorch = kernelConfig.toml.torch.maxver or "99.9"; + versionBetween = + minver: maxver: ver: + builtins.compareVersions ver minver >= 0 && builtins.compareVersions ver maxver <= 0; + supportedBuildSet = + buildSet: + let + backendSupported = kernelConfig.backends.${buildSet.buildConfig.backend}; + frameworkSupported = !kernelConfig.isTvmFfi || (buildSet.buildConfig ? tvmFfiVersion); + cudaVersionSupported = + buildSet.buildConfig.backend != "cuda" + || versionBetween minCuda maxCuda buildSet.buildConfig.cudaVersion; + torchVersionSupported = versionBetween minTorch maxTorch buildSet.buildConfig.torchVersion; + in + backendSupported && cudaVersionSupported && frameworkSupported && torchVersionSupported; in - backendSupported && cudaVersionSupported && frameworkSupported && torchVersionSupported; + builtins.filter supportedBuildSet; + + # Step 2: deduplicate build sets by backend + backend version. + deduplicateForStableAbi = + buildSets: + let + backendKey = + buildSet: + let + inherit (buildSet) buildConfig; + computeVersion = + if buildConfig ? cudaVersion then + buildConfig.cudaVersion + else if buildConfig ? rocmVersion then + buildConfig.rocmVersion + else if buildConfig ? xpuVersion then + buildConfig.xpuVersion + else + ""; + in + "${buildConfig.backend}-${computeVersion}"; + grouped = lib.groupBy backendKey buildSets; + newestPerGroup = lib.mapAttrs ( + _: group: + lib.head ( + lib.sort ( + a: b: builtins.compareVersions a.buildConfig.torchVersion b.buildConfig.torchVersion > 0 + ) group + ) + ) grouped; + in + builtins.attrValues newestPerGroup; + in - builtins.filter supportedBuildSet buildSets; + if kernelConfig.isTorchStableAbi then + deduplicateForStableAbi (buildSetsWithinBounds buildSets) + else + buildSetsWithinBounds buildSets; applicableBuildSets = { path, buildSets }: filterApplicableBuildSets (readKernelConfig path) buildSets; diff --git a/nix-builder/lib/kernel-config.nix b/nix-builder/lib/kernel-config.nix index 1bc0bee86..a365af828 100644 --- a/nix-builder/lib/kernel-config.nix +++ b/nix-builder/lib/kernel-config.nix @@ -25,6 +25,12 @@ in # Is the kernel a tvm-ffi kernel. isTvmFfi = toml ? tvm-ffi; + # Does the kernel use the torch stable ABI. + isTorchStableAbi = lib.attrByPath [ "torch" "stable-abi" ] null toml != null; + + # Torch stable ABI version. + torchStableAbiVersion = lib.attrByPath [ "torch" "stable-abi" ] null toml; + # Kernel backends. backends = let diff --git a/nix-builder/lib/variants/default.nix b/nix-builder/lib/variants/default.nix index 09c08f7c2..ea620ea9e 100644 --- a/nix-builder/lib/variants/default.nix +++ b/nix-builder/lib/variants/default.nix @@ -10,11 +10,9 @@ rec { kernelVariant = kernelConfig: if kernelConfig.isTvmFfi then - tvm-ffi.arch - else if kernelConfig.kernelBackends.${buildConfig.backend} then - torch.arch + tvm-ffi.kernelVariant kernelConfig else - torch.noarch; + torch.kernelVariant kernelConfig; kernelArchVariant = kernelConfig: if kernelConfig.isTvmFfi then tvm-ffi.arch else torch.arch; } diff --git a/nix-builder/lib/variants/torch.nix b/nix-builder/lib/variants/torch.nix index 83b2c0e5d..e656bad3a 100644 --- a/nix-builder/lib/variants/torch.nix +++ b/nix-builder/lib/variants/torch.nix @@ -17,13 +17,27 @@ let "xpu${flattenVersion (lib.versions.majorMinor buildConfig.xpuVersion)}" else "cpu"; + torchString = + stableAbi: + if stableAbi == null then + "torch${flattenVersion (lib.versions.majorMinor buildConfig.torchVersion)}" + else + "torch-stable-abi${flattenVersion (lib.versions.majorMinor stableAbi)}"; in { - arch = - if buildConfig.system == "aarch64-darwin" then + arch = "${torchString null}-${computeString}-${buildConfig.system}"; + noarch = "torch-${buildConfig.backend}"; + + kernelVariant = + kernelConfig: + let + archVariant = kernelConfig.kernelBackends.${buildConfig.backend}; + in + if archVariant && kernelConfig.isTorchStableAbi then + "torch-stable-abi${flattenVersion (lib.versions.majorMinor kernelConfig.torchStableAbiVersion)}-${computeString}-${buildConfig.system}" + else if archVariant then "torch${flattenVersion (lib.versions.majorMinor buildConfig.torchVersion)}-${computeString}-${buildConfig.system}" else - "torch${flattenVersion (lib.versions.majorMinor buildConfig.torchVersion)}-cxx11-${computeString}-${buildConfig.system}"; + "torch-${buildConfig.backend}"; - noarch = "torch-${buildConfig.backend}"; } diff --git a/nix-builder/lib/variants/tvm-ffi.nix b/nix-builder/lib/variants/tvm-ffi.nix index cf868bd03..04360cbd4 100644 --- a/nix-builder/lib/variants/tvm-ffi.nix +++ b/nix-builder/lib/variants/tvm-ffi.nix @@ -17,7 +17,9 @@ let "xpu${flattenVersion (lib.versions.majorMinor buildConfig.xpuVersion)}" else "cpu"; + arch = "tvm-ffi${flattenVersion (lib.versions.majorMinor buildConfig.tvmFfiVersion)}-${computeString}-${buildConfig.system}"; in { - arch = "tvm-ffi${flattenVersion (lib.versions.majorMinor buildConfig.tvmFfiVersion)}-${computeString}-${buildConfig.system}"; + inherit arch; + kernelVariant = _: arch; } From 9b586528e5478d3c20bc7878bbc64916d6fd0519 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Fri, 22 May 2026 12:42:01 +0000 Subject: [PATCH 3/6] kernels: add support `torch-stable-abi` variants This change adds support for `torch-stable-abi` variants: * We now give preference to stable ABI variants. * If there is no exact match for the Torch version, we back off to an older ABI version. --- kernels/src/kernels/variants.py | 64 +++++++++++++-- kernels/tests/test_variants.py | 135 ++++++++++++++++++++++++++++++++ 2 files changed, 193 insertions(+), 6 deletions(-) diff --git a/kernels/src/kernels/variants.py b/kernels/src/kernels/variants.py index 226f432d8..0a8da8c08 100644 --- a/kernels/src/kernels/variants.py +++ b/kernels/src/kernels/variants.py @@ -24,8 +24,6 @@ ) from kernels.compat import has_torch, has_tvm_ffi -BUILD_VARIANT_REGEX = re.compile(r"^(torch\d+\d+|torch-(cpu|cuda|metal|neuron|rocm|xpu)|tvm-ffi\d+\d+)") - @dataclass(unsafe_hash=True) class Torch: @@ -65,6 +63,32 @@ def parse(s: str) -> "Torch": return Torch(version=version, cxx11_abi=cxx11_abi) +@dataclass(unsafe_hash=True) +class TorchStableAbi: + """Stable ABI-versioned Torch framework (arch variants).""" + + # Match the following Torch version encoding: + # + # The first part is `torch-stable-abixy` where x is the major ABI version + # and y the minor ABI version. x can only consist of one digit, y of one + # or more digits. + _VARIANT_REGEX: ClassVar[re.Pattern] = re.compile(r"torch-stable-abi(\d)(\d+)") + + version: Version + + @property + def variant_str(self) -> str: + return f"torch-stable-abi{self.version.major}{self.version.minor}" + + @staticmethod + def parse(s: str) -> "TorchStableAbi": + m = TorchStableAbi._VARIANT_REGEX.fullmatch(s) + if not m: + raise ValueError(f"Invalid Torch stable ABI variant string: {s!r}") + version = Version(f"{m.group(1)}.{m.group(2)}") + return TorchStableAbi(version=version) + + @dataclass(unsafe_hash=True) class TvmFfi: """Versioned tvm-ffi framework (arch variants).""" @@ -141,7 +165,7 @@ def parse(s: str) -> "Noarch": class ArchVariant: """Arch kernel build variant.""" - framework: Torch | TvmFfi + framework: Torch | TorchStableAbi | TvmFfi arch: Arch @property @@ -187,6 +211,11 @@ def parse_variant(variant_str: str) -> Variant: """Parse a variant string into an ArchVariant or NoarchVariant.""" parts = variant_str.split("-") + if variant_str.startswith("torch-stable-abi"): + return ArchVariant( + framework=TorchStableAbi.parse("-".join(parts[0:3])), + arch=Arch.parse(parts[3:]), + ) if parts[0] == "torch": # noarch: e.g. "torch-cpu" return NoarchVariant(framework=TorchNoarch(), arch=Noarch.parse("-".join(parts[1:]))) @@ -396,6 +425,15 @@ def _check_variants( ) ) continue + elif isinstance(v.framework, TorchStableAbi): + if torch_version is None or v.framework.version > torch_version: + result.append( + VariantRejected( + variant=v, + reason=f"Torch stable ABI version ({v.framework.version}) is too new for environment Torch version ({torch_version})", + ) + ) + continue elif isinstance(v.framework, TvmFfi): if v.framework.version != tvm_ffi_version: result.append( @@ -450,6 +488,8 @@ def _sort_variants( """Sort the decision trace in preference order: 1. AcceptedVariant before RejectedVariant. + 2. Torch stable ABI arch kernels, with highest compatible version first, + then highest compatible CUDA version. 2. Torch arch kernels with with the highest compatible CUDA version. 3. tvm-ffi arch kernels with with the highest compatible CUDA version. 4. Torch noarch kernels. @@ -461,17 +501,29 @@ def sort_key(vs: Decision) -> tuple[int, ...]: decision_order = 0 if isinstance(vs, VariantAccepted) else 1 v = vs.variant if isinstance(v, ArchVariant): - framework_order = 0 if isinstance(v.framework, Torch) else 1 + if isinstance(v.framework, TorchStableAbi): + framework_order = 0 + # Prefer newer stable ABI versions. + abi_version_order = ( + -v.framework.version.major, + -v.framework.version.minor, + ) + elif isinstance(v.framework, Torch): + framework_order = 1 + abi_version_order = (0, 0) + else: + framework_order = 2 + abi_version_order = (0, 0) if isinstance(v.arch.backend, (CUDA, ROCm, XPU, CANN)): # Order by backend version in reverse (higher is better). backend_order = -v.arch.backend.version.minor else: backend_order = 0 - return (decision_order, framework_order, backend_order) + return (decision_order, framework_order, *abi_version_order, backend_order) else: assert isinstance(v, NoarchVariant) universal_order = 1 if v.arch.backend_name == "universal" else 0 - return (decision_order, 2, universal_order) + return (decision_order, 2, 0, 0, universal_order) return sorted(variants, key=sort_key) diff --git a/kernels/tests/test_variants.py b/kernels/tests/test_variants.py index 8203906d7..a4a0b315d 100644 --- a/kernels/tests/test_variants.py +++ b/kernels/tests/test_variants.py @@ -48,6 +48,26 @@ ] ) +STABLE_ABI_VARIANT_STRINGS = [ + f"torch-stable-abi{abi_ver}-{backend}-{system}" + for abi_ver in ["211", "29"] + for backend in [ + "cpu", + "cu126", + "cu128", + "cu130", + "rocm63", + "rocm64", + "xpu20252", + ] + for system in ["aarch64-linux", "x86_64-linux"] +] + [ + f"torch-stable-abi{abi_ver}-{backend}-{system}" + for abi_ver in ["211", "29"] + for backend in ["cpu", "metal"] + for system in ["aarch64-darwin"] +] + NOARCH_VARIANT_STRINGS = [ "torch-cpu", "torch-cuda", @@ -97,6 +117,12 @@ def test_arch_variants(variant_str: str): assert parse_variant(variant_str).variant_str == variant_str +@pytest.mark.parametrize("variant_str", STABLE_ABI_VARIANT_STRINGS) +def test_stable_abi_variants(variant_str: str): + # Roundtrip parse and generate variant string. + assert parse_variant(variant_str).variant_str == variant_str + + @pytest.mark.parametrize("variant_str", NOARCH_VARIANT_STRINGS) def test_noarch_variants(variant_str: str): # Roundtrip parse and generate variant string. @@ -392,3 +418,112 @@ def test_resolve_cuda_no_different_major_no_noarch(): assert result == [] assert result == [vs.variant for vs in trace if isinstance(vs, VariantAccepted)] assert {vs.variant for vs in trace} == set(RESOLVE_VARIANTS_NO_NOARCH) + + +RESOLVE_VARIANTS_STABLE_ABI = [ + parse_variant(s) + for s in [ + "torch-stable-abi211-cu128-x86_64-linux", + "torch210-cxx11-cu128-x86_64-linux", + "torch-cuda", + ] +] + + +def test_resolve_stable_abi_accepted(): + # Stable ABI 2.11 is accepted when torch_version == stable ABI version. + result, trace = _resolve_variant_for_system( + variants=RESOLVE_VARIANTS_STABLE_ABI, + selected_backend=CUDA(Version("12.8")), + cpu="x86_64", + os="linux", + torch_version=Version("2.11"), + torch_cxx11_abi=True, + tvm_ffi_version=None, + ) + assert result != [] + assert result[0].variant_str == "torch-stable-abi211-cu128-x86_64-linux" + assert result == [vs.variant for vs in trace if isinstance(vs, VariantAccepted)] + assert {vs.variant for vs in trace} == set(RESOLVE_VARIANTS_STABLE_ABI) + + +def test_resolve_stable_abi_accepted_newer_torch(): + # Stable ABI 2.11 is also accepted when torch_version > stable ABI version. + result, trace = _resolve_variant_for_system( + variants=RESOLVE_VARIANTS_STABLE_ABI, + selected_backend=CUDA(Version("12.8")), + cpu="x86_64", + os="linux", + torch_version=Version("2.12"), + torch_cxx11_abi=True, + tvm_ffi_version=None, + ) + assert result != [] + assert result[0].variant_str == "torch-stable-abi211-cu128-x86_64-linux" + assert result == [vs.variant for vs in trace if isinstance(vs, VariantAccepted)] + assert {vs.variant for vs in trace} == set(RESOLVE_VARIANTS_STABLE_ABI) + + +def test_resolve_stable_abi_rejected_newer_abi(): + # Stable ABI 2.11 is rejected when torch_version < stable ABI version. + result, trace = _resolve_variant_for_system( + variants=RESOLVE_VARIANTS_STABLE_ABI, + selected_backend=CUDA(Version("12.8")), + cpu="x86_64", + os="linux", + torch_version=Version("2.10"), + torch_cxx11_abi=True, + tvm_ffi_version=None, + ) + assert result != [] + assert result[0].variant_str == "torch210-cxx11-cu128-x86_64-linux" + assert result == [vs.variant for vs in trace if isinstance(vs, VariantAccepted)] + assert {vs.variant for vs in trace} == set(RESOLVE_VARIANTS_STABLE_ABI) + + +def test_resolve_stable_abi_newest_version_preferred(): + # When multiple stable ABI versions are accepted, the newest is preferred. + variants = [ + parse_variant(s) + for s in [ + "torch-stable-abi29-cu128-x86_64-linux", + "torch-stable-abi211-cu128-x86_64-linux", + ] + ] + result, trace = _resolve_variant_for_system( + variants=variants, + selected_backend=CUDA(Version("12.8")), + cpu="x86_64", + os="linux", + torch_version=Version("2.12"), + torch_cxx11_abi=True, + tvm_ffi_version=None, + ) + assert result != [] + assert result[0].variant_str == "torch-stable-abi211-cu128-x86_64-linux" + assert result == [vs.variant for vs in trace if isinstance(vs, VariantAccepted)] + assert {vs.variant for vs in trace} == set(variants) + + +def test_resolve_stable_abi_preferred_over_torch(): + # TorchStableAbi variant is preferred over a regular Torch variant of the same version. + variants = [ + parse_variant(s) + for s in [ + "torch-stable-abi211-cu128-x86_64-linux", + "torch211-cxx11-cu128-x86_64-linux", + ] + ] + result, trace = _resolve_variant_for_system( + variants=variants, + selected_backend=CUDA(Version("12.8")), + cpu="x86_64", + os="linux", + torch_version=Version("2.11"), + torch_cxx11_abi=True, + tvm_ffi_version=None, + ) + assert result != [] + assert result[0].variant_str == "torch-stable-abi211-cu128-x86_64-linux" + assert result == [vs.variant for vs in trace if isinstance(vs, VariantAccepted)] + assert {vs.variant for vs in trace} == set(variants) From dcbd776551ad880b627e9a804be9393cc207a9fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Fri, 22 May 2026 12:43:18 +0000 Subject: [PATCH 4/6] examples: add Torch stable ABI example and test in CI --- .github/workflows/build_kernel.yaml | 1 + .github/workflows/build_kernel_rocm.yaml | 4 +- .github/workflows/build_kernel_xpu.yaml | 6 +- examples/kernels/flake.nix | 30 ++--- .../kernels/relu-torch-stable-abi/CARD.md | 56 ++++++++++ .../kernels/relu-torch-stable-abi/build.toml | 65 +++++++++++ .../kernels/relu-torch-stable-abi/flake.nix | 17 +++ .../relu_cpu/relu_cpu.cpp | 59 ++++++++++ .../relu-torch-stable-abi/relu_cuda/relu.cu | 48 ++++++++ .../relu-torch-stable-abi/relu_metal/common.h | 10 ++ .../relu_metal/relu.metal | 17 +++ .../relu-torch-stable-abi/relu_metal/relu.mm | 105 ++++++++++++++++++ .../relu-torch-stable-abi/relu_xpu/relu.cpp | 37 ++++++ .../relu-torch-stable-abi/tests/__init__.py | 0 .../relu-torch-stable-abi/tests/conftest.py | 16 +++ .../relu-torch-stable-abi/tests/test_relu.py | 40 +++++++ .../relu_torch_stable_abi/__init__.py | 17 +++ .../relu_torch_stable_abi/layers/__init__.py | 11 ++ .../torch-ext/torch_binding.cpp | 28 +++++ .../torch-ext/torch_binding.h | 5 + nix-builder/tests/Dockerfile.test-kernel | 1 + nix-builder/tests/run-tests.sh | 3 +- 22 files changed, 556 insertions(+), 20 deletions(-) create mode 100644 examples/kernels/relu-torch-stable-abi/CARD.md create mode 100644 examples/kernels/relu-torch-stable-abi/build.toml create mode 100644 examples/kernels/relu-torch-stable-abi/flake.nix create mode 100644 examples/kernels/relu-torch-stable-abi/relu_cpu/relu_cpu.cpp create mode 100644 examples/kernels/relu-torch-stable-abi/relu_cuda/relu.cu create mode 100644 examples/kernels/relu-torch-stable-abi/relu_metal/common.h create mode 100644 examples/kernels/relu-torch-stable-abi/relu_metal/relu.metal create mode 100644 examples/kernels/relu-torch-stable-abi/relu_metal/relu.mm create mode 100644 examples/kernels/relu-torch-stable-abi/relu_xpu/relu.cpp create mode 100644 examples/kernels/relu-torch-stable-abi/tests/__init__.py create mode 100644 examples/kernels/relu-torch-stable-abi/tests/conftest.py create mode 100644 examples/kernels/relu-torch-stable-abi/tests/test_relu.py create mode 100644 examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/__init__.py create mode 100644 examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/layers/__init__.py create mode 100644 examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.cpp create mode 100644 examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.h diff --git a/.github/workflows/build_kernel.yaml b/.github/workflows/build_kernel.yaml index c626d57c4..18e4e7d77 100644 --- a/.github/workflows/build_kernel.yaml +++ b/.github/workflows/build_kernel.yaml @@ -55,6 +55,7 @@ jobs: cutlass-gemm-tvm-ffi-kernel extra-data relu-kernel + relu-torch-stable-abi-kernel relu-tvm-ffi-kernel relu-kernel-cpu relu-backprop-compile-kernel diff --git a/.github/workflows/build_kernel_rocm.yaml b/.github/workflows/build_kernel_rocm.yaml index eaea43e5a..6d090477a 100644 --- a/.github/workflows/build_kernel_rocm.yaml +++ b/.github/workflows/build_kernel_rocm.yaml @@ -34,7 +34,7 @@ jobs: # For now we only test that there are no regressions in building ROCm # kernels. Also run tests once we have a ROCm runner. - name: Build relu kernel - run: ( cd examples/kernels/relu && nix build .\#redistributable.torch211-cxx11-rocm71-x86_64-linux -L ) + run: ( cd examples/kernels/relu && nix build .\#redistributable.torch211-rocm71-x86_64-linux -L ) - name: Build relu kernel (compiler flags) - run: ( cd examples/kernels/relu-compiler-flags && nix build .\#redistributable.torch211-cxx11-rocm71-x86_64-linux ) + run: ( cd examples/kernels/relu-compiler-flags && nix build .\#redistributable.torch211-rocm71-x86_64-linux ) diff --git a/.github/workflows/build_kernel_xpu.yaml b/.github/workflows/build_kernel_xpu.yaml index 507fa7bcf..b9246f86b 100644 --- a/.github/workflows/build_kernel_xpu.yaml +++ b/.github/workflows/build_kernel_xpu.yaml @@ -34,13 +34,13 @@ jobs: # For now we only test that there are no regressions in building XPU # kernels. Also run tests once we have a XPU runner. - name: Build relu kernel - run: ( cd examples/kernels/relu && nix build .\#redistributable.torch211-cxx11-xpu20253-x86_64-linux -L ) + run: ( cd examples/kernels/relu && nix build .\#redistributable.torch211-xpu20253-x86_64-linux -L ) - name: Build relu tvm-ffi kernel run: ( cd examples/kernels/relu-tvm-ffi && nix build .\#redistributable.tvm-ffi01-xpu20253-x86_64-linux -L ) - name: Build relu kernel (compiler flags) - run: ( cd examples/kernels/relu-compiler-flags && nix build .\#redistributable.torch211-cxx11-xpu20253-x86_64-linux ) + run: ( cd examples/kernels/relu-compiler-flags && nix build .\#redistributable.torch211-xpu20253-x86_64-linux ) - name: Build cutlass-gemm kernel - run: ( cd examples/kernels/cutlass-gemm && nix build .\#redistributable.torch211-cxx11-xpu20253-x86_64-linux -L ) + run: ( cd examples/kernels/cutlass-gemm && nix build .\#redistributable.torch211-xpu20253-x86_64-linux -L ) diff --git a/examples/kernels/flake.nix b/examples/kernels/flake.nix index 1cbdf618c..ac8b377b0 100644 --- a/examples/kernels/flake.nix +++ b/examples/kernels/flake.nix @@ -26,16 +26,22 @@ # system and flake outputs. # - torchVersions: optional override for the torchVersions argument ciKernels = [ + { + name = "cpp20-symbols-kernel"; + path = ./cpp20-symbols; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cpu-${sys}"}; + } { name = "relu-kernel"; path = ./relu; - drv = - sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-${cudaVersion}-${sys}"}; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-${cudaVersion}-${sys}"}; } { - name = "cpp20-symbols-kernel"; - path = ./cpp20-symbols; - drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-cpu-${sys}"}; + name = "relu-torch-stable-abi-kernel"; + path = ./relu-torch-stable-abi; + drv = + sys: out: + out.packages.${sys}.redistributable.${"torch-stable-abi${torchVersion}-${cudaVersion}-${sys}"}; } { name = "relu-tvm-ffi-kernel"; @@ -46,19 +52,17 @@ { name = "extra-data"; path = ./extra-data; - drv = - sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-${cudaVersion}-${sys}"}; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-${cudaVersion}-${sys}"}; } { name = "relu-kernel-cpu"; path = ./relu; - drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-cpu-${sys}"}; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cpu-${sys}"}; } { name = "cutlass-gemm-kernel"; path = ./cutlass-gemm; - drv = - sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-${cudaVersion}-${sys}"}; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-${cudaVersion}-${sys}"}; } { name = "cutlass-gemm-tvm-ffi-kernel"; @@ -69,8 +73,7 @@ { name = "relu-backprop-compile-kernel"; path = ./relu-backprop-compile; - drv = - sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-${cudaVersion}-${sys}"}; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-${cudaVersion}-${sys}"}; } { name = "silu-and-mul-kernel"; @@ -97,8 +100,7 @@ { name = "relu-compiler-flags"; path = ./relu-compiler-flags; - drv = - sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-cxx11-${cudaVersion}-${sys}"}; + drv = sys: out: out.packages.${sys}.redistributable.${"torch${torchVersion}-${cudaVersion}-${sys}"}; } { # Check that we can build an arch dev shell. diff --git a/examples/kernels/relu-torch-stable-abi/CARD.md b/examples/kernels/relu-torch-stable-abi/CARD.md new file mode 100644 index 000000000..c7c707151 --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/CARD.md @@ -0,0 +1,56 @@ +--- +library_name: kernels +{% if license %}license: {{ license }} +{% endif %}--- + +This is the repository card of {{ repo_id }} that has been pushed on the Hub. It was built to be used with the [`kernels` library](https://github.com/huggingface/kernels). This card was automatically generated. + +## How to use +{% if functions %} + +```python +# make sure `kernels` is installed: `pip install -U kernels` +from kernels import get_kernel + +kernel_module = get_kernel("{{ repo_id }}", version={{ version }}) +{{ functions[0] }} = kernel_module.{{ functions[0] }} + +{{ functions[0] }}(...) +``` +{% else %} + +Usage example not available. +{% endif %} + +## Available functions +{% if functions %} +{% for func in functions %} +- `{{ func }}` +{% endfor %} +{% else %} + +Function list not available. +{% endif %} +{% if layers %} + +## Available layers +{% for layer in layers %} +- `{{ layer }}` +{% endfor %} +{% endif %} + +## Benchmarks +{% if has_benchmark %} + +Benchmarking script is available for this kernel. Run `kernels benchmark {{ repo_id }} --version {{ version }}`. +{% else %} + +No benchmark available yet. +{% endif %} +{% if upstream %} + +## Source code + +Source code of this kernel originally comes from {{ upstream }} and it was repurposed for compatibility with `kernels`. +{% endif %} + diff --git a/examples/kernels/relu-torch-stable-abi/build.toml b/examples/kernels/relu-torch-stable-abi/build.toml new file mode 100644 index 000000000..84f7931cb --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/build.toml @@ -0,0 +1,65 @@ +[general] +name = "relu-torch-stable-abi" +version = 1 +license = "Apache-2.0" +backends = [ + "cpu", + "cuda", + "metal", + "rocm", + "xpu", +] + +[general.hub] +repo-id = "kernels-test/relu-torch-stable-abi" + +[torch] +stable-abi = "2.11" +src = [ + "torch-ext/torch_binding.cpp", + "torch-ext/torch_binding.h", +] + +[kernel.relu_xpu] +backend = "xpu" +depends = ["torch"] +src = ["relu_xpu/relu.cpp"] + + +# Converting metal to the Torch stable ABI requires additional APIs to get +# the command buffer and dispatch queue. +# +# [kernel.relu_metal] +# backend = "metal" +# depends = ["torch"] +# src = [ +# "relu_metal/relu.mm", +# "relu_metal/relu.metal", +# "relu_metal/common.h", +#] + +[kernel.relu_rocm] +backend = "rocm" +depends = ["torch"] +rocm-archs = [ + "gfx906", + "gfx908", + "gfx90a", + "gfx940", + "gfx941", + "gfx942", + "gfx1030", + "gfx1100", + "gfx1101", +] +src = ["relu_cuda/relu.cu"] + +[kernel.relu_cpu] +backend = "cpu" +depends = ["torch"] +src = ["relu_cpu/relu_cpu.cpp"] + +[kernel.relu] +backend = "cuda" +depends = ["torch"] +src = ["relu_cuda/relu.cu"] diff --git a/examples/kernels/relu-torch-stable-abi/flake.nix b/examples/kernels/relu-torch-stable-abi/flake.nix new file mode 100644 index 000000000..41e51eef7 --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/flake.nix @@ -0,0 +1,17 @@ +{ + description = "Flake for ReLU kernel"; + + inputs = { + kernel-builder.url = "path:../../.."; + }; + + outputs = + { + self, + kernel-builder, + }: + kernel-builder.lib.genKernelFlakeOutputs { + inherit self; + path = ./.; + }; +} diff --git a/examples/kernels/relu-torch-stable-abi/relu_cpu/relu_cpu.cpp b/examples/kernels/relu-torch-stable-abi/relu_cpu/relu_cpu.cpp new file mode 100644 index 000000000..97950c036 --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/relu_cpu/relu_cpu.cpp @@ -0,0 +1,59 @@ +#include + +#ifdef __SSE__ +#include +#endif + +#ifdef __ARM_NEON +#include +#endif + +// NOTE: This is a minimal example kernel that is not optimized for +// performance, so we do not care about unaligned loads/stores. + +#ifdef __SSE__ +void relu_forward_sse(float* out, const float* input, size_t size) { + size_t i = 0; + + for (; i + 4 <= size; i += 4) { + __m128 vec_input = _mm_loadu_ps(input + i); + __m128 vec_zero = _mm_setzero_ps(); + __m128 vec_output = _mm_max_ps(vec_input, vec_zero); + _mm_storeu_ps(out + i, vec_output); + } + + for (; i < size; ++i) { + out[i] = input[i] > 0 ? input[i] : 0; + } +} +#endif + +#ifdef __ARM_NEON +void relu_forward_neon(float* out, const float* input, size_t size) { + size_t i = 0; + + for (; i + 4 <= size; i += 4) { + float32x4_t vec_input = vld1q_f32(input + i); + float32x4_t vec_output = vmaxq_f32(vec_input, vdupq_n_f32(0)); + vst1q_f32(out + i, vec_output); + } + + for (; i < size; ++i) { + out[i] = input[i] > 0 ? input[i] : 0; + } +} +#endif + +void relu(torch::stable::Tensor &out, torch::stable::Tensor const &input) { + STD_TORCH_CHECK(out.scalar_type() == torch::headeronly::ScalarType::Float, "Output tensor must be of dtype float"); + STD_TORCH_CHECK(input.scalar_type() == torch::headeronly::ScalarType::Float, "Input tensor must be of dtype float"); + STD_TORCH_CHECK(out.numel() == input.numel(), "Input and output tensors must have the same number of elements"); + +#if defined(__SSE__) + relu_forward_sse(static_cast(out.data_ptr()), static_cast(input.data_ptr()), input.numel()); +#elif defined(__ARM_NEON) + relu_forward_neon(static_cast(out.data_ptr()), static_cast(input.data_ptr()), input.numel()); +#else + #error "Unsupported architecture; please use a CPU with SSE or ARM NEON support." +#endif +} diff --git a/examples/kernels/relu-torch-stable-abi/relu_cuda/relu.cu b/examples/kernels/relu-torch-stable-abi/relu_cuda/relu.cu new file mode 100644 index 000000000..a0565f648 --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/relu_cuda/relu.cu @@ -0,0 +1,48 @@ +#include +#include + +// The shim's definition is guarded by USE_CUDA, so define here. +extern "C" AOTITorchError aoti_torch_get_current_cuda_stream(int32_t device_index, void** ret_stream); + +#include + +__global__ void relu_kernel(float *__restrict__ out, + float const *__restrict__ input, const int d) { + const int64_t token_idx = blockIdx.x; + for (int64_t idx = threadIdx.x; idx < d; idx += blockDim.x) { + auto x = input[token_idx * d + idx]; + out[token_idx * d + idx] = x > 0.0f ? x : 0.0f; + } +} + +void relu(torch::stable::Tensor &out, torch::stable::Tensor const &input) { + STD_TORCH_CHECK(input.is_cuda(), "input must be a CUDA tensor"); + STD_TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); + STD_TORCH_CHECK(input.scalar_type() == torch::headeronly::ScalarType::Float && + out.scalar_type() == torch::headeronly::ScalarType::Float, + "relu_kernel only supports float32"); + + STD_TORCH_CHECK(input.sizes().equals(out.sizes()), + "Tensors must have the same shape."); + + STD_TORCH_CHECK(input.scalar_type() == out.scalar_type(), + "Tensors must have the same data type."); + + STD_TORCH_CHECK(input.device() == out.device(), + "Tensors must be on the same device."); + + if (input.numel() == 0) { + return; + } + + int d = input.size(-1); + int64_t num_tokens = input.numel() / d; + dim3 grid(num_tokens); + dim3 block(std::min(d, 1024)); + const torch::stable::accelerator::DeviceGuard device_guard(input.get_device_index()); + void* stream_ptr = nullptr; + TORCH_ERROR_CODE_CHECK(aoti_torch_get_current_cuda_stream(input.get_device_index(), &stream_ptr)); + const cudaStream_t stream = static_cast(stream_ptr); + relu_kernel<<>>(static_cast(out.data_ptr()), + static_cast(input.data_ptr()), d); +} diff --git a/examples/kernels/relu-torch-stable-abi/relu_metal/common.h b/examples/kernels/relu-torch-stable-abi/relu_metal/common.h new file mode 100644 index 000000000..1b891fade --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/relu_metal/common.h @@ -0,0 +1,10 @@ +#ifndef COMMON_H +#define COMMON_H + +#include +using namespace metal; + +// Common constants and utilities for Metal kernels +constant float RELU_THRESHOLD = 0.0f; + +#endif // COMMON_H \ No newline at end of file diff --git a/examples/kernels/relu-torch-stable-abi/relu_metal/relu.metal b/examples/kernels/relu-torch-stable-abi/relu_metal/relu.metal new file mode 100644 index 000000000..286b46fee --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/relu_metal/relu.metal @@ -0,0 +1,17 @@ +#include +#include "common.h" +using namespace metal; + +kernel void relu_forward_kernel_float(device const float *inA [[buffer(0)]], + device float *outC [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + // Explicitly write to output + outC[index] = max(RELU_THRESHOLD, inA[index]); +} + +kernel void relu_forward_kernel_half(device const half *inA [[buffer(0)]], + device half *outC [[buffer(1)]], + uint index [[thread_position_in_grid]]) { + // Explicitly write to output + outC[index] = max(static_cast(0.0), inA[index]); +} \ No newline at end of file diff --git a/examples/kernels/relu-torch-stable-abi/relu_metal/relu.mm b/examples/kernels/relu-torch-stable-abi/relu_metal/relu.mm new file mode 100644 index 000000000..7636737bf --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/relu_metal/relu.mm @@ -0,0 +1,105 @@ +#include + +#import +#import + +// Include the auto-generated header with embedded metallib +#ifdef EMBEDDED_METALLIB_HEADER +#include EMBEDDED_METALLIB_HEADER +#else +#error "EMBEDDED_METALLIB_HEADER not defined" +#endif + +static inline id getMTLBufferStorage(const torch::Tensor &tensor) { + return __builtin_bit_cast(id, tensor.storage().data()); +} + + +torch::Tensor &dispatchReluKernel(torch::Tensor const &input, + torch::Tensor &output) { + @autoreleasepool { + id device = MTLCreateSystemDefaultDevice(); + + int numThreads = input.numel(); + + // Load the embedded Metal library from memory + NSError *error = nil; + id customKernelLibrary = EMBEDDED_METALLIB_NAMESPACE::createLibrary(device, &error); + TORCH_CHECK(customKernelLibrary, + "Failed to create Metal library from embedded data: ", + error.localizedDescription.UTF8String); + + std::string kernel_name = + std::string("relu_forward_kernel_") + + (input.scalar_type() == torch::kFloat ? "float" : "half"); + id customReluFunction = [customKernelLibrary + newFunctionWithName:[NSString + stringWithUTF8String:kernel_name.c_str()]]; + TORCH_CHECK(customReluFunction, + "Failed to create function state object for ", + kernel_name.c_str()); + + id reluPSO = + [device newComputePipelineStateWithFunction:customReluFunction + error:&error]; + TORCH_CHECK(reluPSO, error.localizedDescription.UTF8String); + + id commandBuffer = torch::mps::get_command_buffer(); + TORCH_CHECK(commandBuffer, "Failed to retrieve command buffer reference"); + + dispatch_queue_t serialQueue = torch::mps::get_dispatch_queue(); + + dispatch_sync(serialQueue, ^() { + id computeEncoder = + [commandBuffer computeCommandEncoder]; + TORCH_CHECK(computeEncoder, "Failed to create compute command encoder"); + + [computeEncoder setComputePipelineState:reluPSO]; + [computeEncoder setBuffer:getMTLBufferStorage(input) + offset:input.storage_offset() * input.element_size() + atIndex:0]; + [computeEncoder setBuffer:getMTLBufferStorage(output) + offset:output.storage_offset() * output.element_size() + atIndex:1]; + + MTLSize gridSize = MTLSizeMake(numThreads, 1, 1); + + NSUInteger threadGroupSize = reluPSO.maxTotalThreadsPerThreadgroup; + if (threadGroupSize > numThreads) { + threadGroupSize = numThreads; + } + MTLSize threadgroupSize = MTLSizeMake(threadGroupSize, 1, 1); + + [computeEncoder dispatchThreads:gridSize + threadsPerThreadgroup:threadgroupSize]; + + [computeEncoder endEncoding]; + + torch::mps::commit(); + }); + } + + return output; +} + +void relu(torch::Tensor &out, torch::Tensor const &input) { + TORCH_CHECK(input.device().is_mps(), "input must be a MPS tensor"); + TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); + TORCH_CHECK(input.scalar_type() == torch::kFloat || + input.scalar_type() == torch::kHalf, + "Unsupported data type: ", input.scalar_type()); + + TORCH_CHECK(input.sizes() == out.sizes(), + "Tensors must have the same shape. Got input shape: ", + input.sizes(), " and output shape: ", out.sizes()); + + TORCH_CHECK(input.scalar_type() == out.scalar_type(), + "Tensors must have the same data type. Got input dtype: ", + input.scalar_type(), " and output dtype: ", out.scalar_type()); + + TORCH_CHECK(input.device() == out.device(), + "Tensors must be on the same device. Got input device: ", + input.device(), " and output device: ", out.device()); + + dispatchReluKernel(input, out); +} diff --git a/examples/kernels/relu-torch-stable-abi/relu_xpu/relu.cpp b/examples/kernels/relu-torch-stable-abi/relu_xpu/relu.cpp new file mode 100644 index 000000000..8a2f9ca9f --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/relu_xpu/relu.cpp @@ -0,0 +1,37 @@ +#include +#include + +using namespace sycl; + +void relu_xpu_impl(torch::stable::Tensor& output, const torch::stable::Tensor& input) { + // Create SYCL queue directly + sycl::queue queue; + + auto input_ptr = input.const_data_ptr(); + auto output_ptr = output.mutable_data_ptr(); + auto numel = input.numel(); + + // Launch SYCL kernel + queue.parallel_for(range<1>(numel), [=](id<1> idx) { + auto i = idx[0]; + output_ptr[i] = input_ptr[i] > 0.0f ? input_ptr[i] : 0.0f; + }).wait(); +} + +void relu(torch::stable::Tensor& out, const torch::stable::Tensor& input) { + STD_TORCH_CHECK(input.device().type() == torch::headeronly::DeviceType::XPU, "input must be a XPU tensor"); + STD_TORCH_CHECK(input.is_contiguous(), "input must be contiguous"); + STD_TORCH_CHECK(input.scalar_type() == torch::headeronly::ScalarType::Float, + "Unsupported data type: ", input.scalar_type()); + + STD_TORCH_CHECK(input.sizes().equals(out.sizes()), + "Tensors must have the same shape."); + + STD_TORCH_CHECK(input.scalar_type() == out.scalar_type(), + "Tensors must have the same data type."); + + STD_TORCH_CHECK(input.device() == out.device(), + "Tensors must be on the same device."); + + relu_xpu_impl(out, input); +} diff --git a/examples/kernels/relu-torch-stable-abi/tests/__init__.py b/examples/kernels/relu-torch-stable-abi/tests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/examples/kernels/relu-torch-stable-abi/tests/conftest.py b/examples/kernels/relu-torch-stable-abi/tests/conftest.py new file mode 100644 index 000000000..8adf60e5b --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/tests/conftest.py @@ -0,0 +1,16 @@ +import platform + +import pytest +import torch + + +@pytest.fixture(scope="session") +def device() -> torch.device: + if platform.system() == "Darwin": + return torch.device("mps") + elif hasattr(torch, "xpu") and torch.xpu.is_available(): + return torch.device("xpu") + elif torch.version.cuda is not None and torch.cuda.is_available(): + return torch.device("cuda") + else: + return torch.device("cpu") diff --git a/examples/kernels/relu-torch-stable-abi/tests/test_relu.py b/examples/kernels/relu-torch-stable-abi/tests/test_relu.py new file mode 100644 index 000000000..e8c66af7d --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/tests/test_relu.py @@ -0,0 +1,40 @@ +import pytest +import torch +import torch.nn.functional as F + +import relu_torch_stable_abi + + +@pytest.mark.kernels_ci +def test_relu(device): + x = torch.randn(1024, 1024, dtype=torch.float32, device=device) + torch.testing.assert_close( + F.relu(x), relu_torch_stable_abi.relu(x, torch.empty_like(x)) + ) + + +@pytest.mark.kernels_ci +def test_relu_views(device): + x = torch.arange(-20, 20, device=device, dtype=torch.float32) + + # Keep buffers and fill on each iteration. Stable pointers make C++-side + # pointer inspection esier. + out = torch.empty_like(x) + out_check = torch.empty_like(x) + + for i in range(41): + # Put a sentineal value in the output. + out.fill_(42) + out_check.fill_(42) + + relu_torch_stable_abi.relu(x[i:], out[i:]) + out_check[i:] = F.relu(x[i:]) + + torch.testing.assert_close(out, out_check) + + +@pytest.mark.kernels_ci +def test_relu_layer(device): + x = torch.randn(1024, 1024, dtype=torch.float32, device=device) + layer = relu_torch_stable_abi.layers.ReLU() + torch.testing.assert_close(F.relu(x), layer(x)) diff --git a/examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/__init__.py b/examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/__init__.py new file mode 100644 index 000000000..e77f9a69a --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/__init__.py @@ -0,0 +1,17 @@ +from typing import Optional + +import torch + +from ._ops import ops + +from . import layers + + +def relu(x: torch.Tensor, out: Optional[torch.Tensor] = None) -> torch.Tensor: + if out is None: + out = torch.empty_like(x) + ops.relu(out, x) + return out + + +__all__ = ["relu", "layers"] diff --git a/examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/layers/__init__.py b/examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/layers/__init__.py new file mode 100644 index 000000000..6105a1910 --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/torch-ext/relu_torch_stable_abi/layers/__init__.py @@ -0,0 +1,11 @@ +import torch +import torch.nn as nn + +from .._ops import ops + + +class ReLU(nn.Module): + def forward(self, x: torch.Tensor) -> torch.Tensor: + out = torch.empty_like(x) + ops.relu(out, x) + return out diff --git a/examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.cpp b/examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.cpp new file mode 100644 index 000000000..82789f6cf --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.cpp @@ -0,0 +1,28 @@ +#include + +#include "registration.h" +#include "torch_binding.h" + +STABLE_TORCH_LIBRARY_EXPAND(TORCH_EXTENSION_NAME, ops) { + ops.def("relu(Tensor! out, Tensor input) -> ()"); +} + +#if defined(CPU_KERNEL) +STABLE_TORCH_LIBRARY_IMPL_EXPAND(TORCH_EXTENSION_NAME, CPU, ops) { + ops.impl("relu", TORCH_BOX(&relu)); +} +#elif defined(CUDA_KERNEL) || defined(ROCM_KERNEL) +STABLE_TORCH_LIBRARY_IMPL_EXPAND(TORCH_EXTENSION_NAME, CUDA, ops) { + ops.impl("relu", TORCH_BOX(&relu)); +} +#elif defined(METAL_KERNEL) +STABLE_TORCH_LIBRARY_IMPL_EXPAND(TORCH_EXTENSION_NAME, MPS, ops) { + ops.impl("relu", TORCH_BOX(&relu)); +} +#elif defined(XPU_KERNEL) +STABLE_TORCH_LIBRARY_IMPL_EXPAND(TORCH_EXTENSION_NAME, XPU, ops) { + ops.impl("relu", TORCH_BOX(&relu)); +} +#endif + +REGISTER_EXTENSION(TORCH_EXTENSION_NAME) diff --git a/examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.h b/examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.h new file mode 100644 index 000000000..7964393d0 --- /dev/null +++ b/examples/kernels/relu-torch-stable-abi/torch-ext/torch_binding.h @@ -0,0 +1,5 @@ +#pragma once + +#include + +void relu(torch::stable::Tensor &out, torch::stable::Tensor const &input); diff --git a/nix-builder/tests/Dockerfile.test-kernel b/nix-builder/tests/Dockerfile.test-kernel index 16916f7ca..fc6f3e5b4 100644 --- a/nix-builder/tests/Dockerfile.test-kernel +++ b/nix-builder/tests/Dockerfile.test-kernel @@ -62,6 +62,7 @@ RUN uv add "apache-tvm-ffi~=0.1.9" numpy pytest # Copy kernels and tests COPY relu-kernel ./relu-kernel +COPY relu-torch-stable-abi-kernel ./relu-torch-stable-abi-kernel COPY relu-tvm-ffi-kernel ./relu-tvm-ffi-kernel COPY relu-kernel-cpu ./relu-kernel-cpu COPY cutlass-gemm-kernel ./cutlass-gemm-kernel diff --git a/nix-builder/tests/run-tests.sh b/nix-builder/tests/run-tests.sh index f4e7428d7..aea848fca 100644 --- a/nix-builder/tests/run-tests.sh +++ b/nix-builder/tests/run-tests.sh @@ -4,6 +4,7 @@ set -euo pipefail # Expand to build variant directories. EXTRA_DATA_PATH=$(echo extra-data/torch*) RELU_PATH=$(echo relu-kernel/torch*) +RELU_TORCH_STABLE_ABI_PATH=$(echo relu-torch-stable-abi-kernel/torch*) RELU_TVM_FFI_PATH=$(echo relu-tvm-ffi-kernel/tvm-ffi*) CUTLASS_PATH=$(echo cutlass-gemm-kernel/torch*) CUTLASS_TVM_FFI_PATH=$(echo cutlass-gemm-tvm-ffi-kernel/tvm-ffi*) @@ -11,7 +12,7 @@ SILU_MUL_PATH=$(echo silu-and-mul-kernel/torch*) RELU_CPU_PATH=$(echo relu-kernel-cpu/torch*) CPP20_SYMBOLS_PATH=$(echo cpp20-symbols-kernel/torch*) -PYTHONPATH="$EXTRA_DATA_PATH:$RELU_PATH:$RELU_TVM_FFI_PATH:$CUTLASS_PATH:$CUTLASS_TVM_FFI_PATH" \ +PYTHONPATH="$EXTRA_DATA_PATH:$RELU_PATH:$RELU_TORCH_STABLE_ABI_PATH:$RELU_TVM_FFI_PATH:$CUTLASS_PATH:$CUTLASS_TVM_FFI_PATH" \ .venv/bin/pytest extra_data_tests relu_tests relu_tvm_ffi_tests cutlass_gemm_tests cutlass_gemm_tvm_ffi_tests # We only care about importing, the kernel is trivial. From 23fe07c59ff18c003869d73b9ceb01b02123f136 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Fri, 22 May 2026 12:48:23 +0000 Subject: [PATCH 5/6] docs: document the `stable-abi` option --- docs/source/builder/writing-kernels.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index aa38a192e..d8bce8fe7 100644 --- a/docs/source/builder/writing-kernels.md +++ b/docs/source/builder/writing-kernels.md @@ -227,6 +227,12 @@ options: non-compliant kernels if the version range does not correspond to the [required variants](build-variants.md). - `minver` (optional): only build for this Torch version and later. Use cautiously, since this option produces non-compliant kernels if the version range does not correspond to the [required variants](build-variants.md). +- `stable-abi` (**experimental**): when set to a Torch version (e.g. + `"2.11"`), the kernel is built using the Torch stable ABI. This + requires that the kernel itself only + [stable ABI headers](https://docs.pytorch.org/docs/2.12/notes/libtorch_stable_abi.html). + For an example, see the [`relu-torch-stable-abi`](https://github.com/huggingface/kernels/tree/main/examples/kernels/relu-torch-stable-abi) + example kernel. ### `kernel.` @@ -277,7 +283,6 @@ are available: - `cxx-flags`: a list of additional flags to be passed to the C++ compiler. - ## Torch bindings ### Defining bindings From 0404da3fc11a6dc9c3d664974eb766bf0cfb9e94 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl=20de=20Kok?= Date: Mon, 25 May 2026 17:02:38 +0200 Subject: [PATCH 6/6] Documentation fixes Co-authored-by: Sayak Paul --- docs/source/builder/writing-kernels.md | 2 +- kernel-builder/src/pyproject/templates/torch/preamble.cmake | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index d8bce8fe7..4ba9fe717 100644 --- a/docs/source/builder/writing-kernels.md +++ b/docs/source/builder/writing-kernels.md @@ -229,7 +229,7 @@ options: non-compliant kernels if the version range does not correspond to the [required variants](build-variants.md). - `stable-abi` (**experimental**): when set to a Torch version (e.g. `"2.11"`), the kernel is built using the Torch stable ABI. This - requires that the kernel itself only + requires that the kernel itself only use [stable ABI headers](https://docs.pytorch.org/docs/2.12/notes/libtorch_stable_abi.html). For an example, see the [`relu-torch-stable-abi`](https://github.com/huggingface/kernels/tree/main/examples/kernels/relu-torch-stable-abi) example kernel. diff --git a/kernel-builder/src/pyproject/templates/torch/preamble.cmake b/kernel-builder/src/pyproject/templates/torch/preamble.cmake index 0620a2e00..4bbb6736b 100644 --- a/kernel-builder/src/pyproject/templates/torch/preamble.cmake +++ b/kernel-builder/src/pyproject/templates/torch/preamble.cmake @@ -68,7 +68,7 @@ endif() {% if stable_abi %} if (TORCH_VERSION VERSION_LESS {{ stable_abi }}) message(FATAL_ERROR "Torch version ${TORCH_VERSION} is less than the stable ABI " - "version {{ stable_abi }}. Cannot build with stable ABI targeting a newer Torch.") + "version {{ stable_abi }}. Cannot build with stable ABI targeting a newer version of Torch.") endif() # From the Torch docs: TORCH_TARGET_VERSION (((0ULL + major) << 56) | ((0ULL + minor) << 48))