From c440ae7f92fbb6fb142376c16a55bed8f56a16fe Mon Sep 17 00:00:00 2001 From: David Holtz Date: Thu, 15 Oct 2026 18:11:36 +0000 Subject: [PATCH 1/5] feat: support rust gpu --- docs/source/builder/writing-kernels.md | 2 +- flake.lock | 6 +- kernel-builder/src/pyproject/kernel.rs | 78 +++++++++++++++++++ .../kernel-component/rust-cuda.cmake | 9 +++ .../src/pyproject/templates/rust.cmake | 66 +++++++++++++++- kernel-builder/tests/rust-components.cmake | 60 ++++++++++++++ kernels-common/src/config/mod.rs | 75 +++++++++++++++++- kernels-common/src/config/v6.rs | 52 ++++++++++++- nix-builder/lib/build.nix | 3 + nix-builder/lib/extension/tvm-ffi/arch.nix | 70 ++++++++++++----- .../lib/extension/tvm-ffi/rust-cuda.nix | 60 ++++++++++++++ nix-builder/lib/source-set.nix | 7 +- 12 files changed, 454 insertions(+), 34 deletions(-) create mode 100644 kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake create mode 100644 kernel-builder/tests/rust-components.cmake create mode 100644 nix-builder/lib/extension/tvm-ffi/rust-cuda.nix diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index 48c9bddf..9c57b294 100644 --- a/docs/source/builder/writing-kernels.md +++ b/docs/source/builder/writing-kernels.md @@ -318,7 +318,7 @@ The following options can be set for a kernel: - `language` (required): the language and compute backend of the kernel, as `-`. The currently supported values are `cpp-cpu`, - `cpp-cuda`, `cpp-metal`, `cpp-rocm`, `cpp-xpu`, and `rust-cpu`. + `cpp-cuda`, `cpp-metal`, `cpp-rocm`, `cpp-xpu`, `rust-cpu`, and `rust-cuda`. **The `cpu` backend is currently experimental and might still change.** - `depends` (required): a list of dependencies. The supported dependencies are listed in [`cpp-deps.nix`](https://github.com/huggingface/kernels/blob/main/builder/lib/cpp-deps.nix). diff --git a/flake.lock b/flake.lock index 47af4d8d..edadde8f 100644 --- a/flake.lock +++ b/flake.lock @@ -64,11 +64,11 @@ ] }, "locked": { - "lastModified": 1789543870, - "narHash": "sha256-45ikFmtfgBZgMePIm4GevJ9VjDSWO3PGQgOuuwHDpes=", + "lastModified": 1792048409, + "narHash": "sha256-ZcwtnGWuY65NQ75W1LZ99gIaFBgC0Sm+TCs1ZEabw0U=", "owner": "oxalica", "repo": "rust-overlay", - "rev": "35ca0490d13a3d38c4602d0eb9600a30fa63a367", + "rev": "e9d12b9d8266ed9afdc5add5537ec8b5f789645c", "type": "github" }, "original": { diff --git a/kernel-builder/src/pyproject/kernel.rs b/kernel-builder/src/pyproject/kernel.rs index 43fa036b..aa603f92 100644 --- a/kernel-builder/src/pyproject/kernel.rs +++ b/kernel-builder/src/pyproject/kernel.rs @@ -40,6 +40,26 @@ fn render_kernel_component( Kernel::RustCpu { cargo_manifest, .. } => { render_kernel_component_rust(env, kernel_name, cargo_manifest, write)? } + Kernel::RustCuda { + cargo_manifest, + device_manifest, + ptx_dir, + cuda_capabilities, + .. + } => { + env.get_template("kernel-component/rust-cuda.cmake")? + .render_captured_to( + context! { + name => kernel_name, + manifest_path => cargo_manifest, + device_manifest => device_manifest, + ptx_dir => ptx_dir, + cuda_capabilities => cuda_capabilities, + }, + &mut *write, + )?; + write.write_all(b"\n")?; + } Kernel::CppCuda { .. } => { render_kernel_component_cuda(env, kernel_name, kernel, sources, write)? } @@ -238,3 +258,61 @@ fn render_kernel_component_xpu( Ok(()) } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rust_components_render_for_their_backend() { + let mut env = Environment::new(); + minijinja_embed::load_templates!(&mut env); + for (kernel, backend, device) in [ + ( + Kernel::RustCpu { + cargo_manifest: "host/Cargo.toml".into(), + depends: vec![], + src: vec![], + }, + "CPU", + false, + ), + ( + Kernel::RustCuda { + cargo_manifest: "host/Cargo.toml".into(), + device_manifest: Some("device/Cargo.toml".into()), + ptx_dir: Some("ptx".into()), + cuda_capabilities: Some(vec!["8.0".into(), "9.0".into()]), + depends: vec![], + src: vec![], + }, + "CUDA", + true, + ), + ( + Kernel::RustCuda { + cargo_manifest: "host/Cargo.toml".into(), + device_manifest: None, + ptx_dir: None, + cuda_capabilities: None, + depends: vec![], + src: vec![], + }, + "CUDA", + false, + ), + ] { + let mut rendered = vec![]; + render_kernel_component(&env, "example", &kernel, &mut rendered).unwrap(); + let rendered = String::from_utf8(rendered).unwrap(); + assert!(rendered.contains(&format!("if(GPU_LANG STREQUAL \"{backend}\")"))); + assert!(rendered.contains("MANIFEST_PATH \"host/Cargo.toml\"")); + assert_eq!(rendered.contains("DEVICE_MANIFEST"), device); + if device { + assert!(rendered.contains("DEVICE_MANIFEST \"device/Cargo.toml\"")); + assert!(rendered.contains("PTX_DIR \"ptx\"")); + assert!(rendered.contains("CUDA_CAPABILITIES 8.0 9.0")); + } + } + } +} diff --git a/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake b/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake new file mode 100644 index 00000000..7664b3cf --- /dev/null +++ b/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake @@ -0,0 +1,9 @@ +if(GPU_LANG STREQUAL "CUDA") + rust_kernel_component(RUST_KERNEL_LIBS RUST_KERNEL_TARGETS + NAME {{ name }} + MANIFEST_PATH "{{ manifest_path }}" + {% if device_manifest %}DEVICE_MANIFEST "{{ device_manifest }}"{% endif %} + {% if ptx_dir %}PTX_DIR "{{ ptx_dir }}"{% endif %} + {% if cuda_capabilities %}CUDA_CAPABILITIES {{ cuda_capabilities | join(" ") }}{% endif %} + ) +endif() diff --git a/kernel-builder/src/pyproject/templates/rust.cmake b/kernel-builder/src/pyproject/templates/rust.cmake index 727fff42..1c2a056b 100644 --- a/kernel-builder/src/pyproject/templates/rust.cmake +++ b/kernel-builder/src/pyproject/templates/rust.cmake @@ -1,5 +1,5 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) - cmake_parse_arguments(KERNEL "" "NAME;MANIFEST_PATH" "" ${ARGN}) + cmake_parse_arguments(KERNEL "" "NAME;MANIFEST_PATH;DEVICE_MANIFEST;PTX_DIR" "CUDA_CAPABILITIES" ${ARGN}) if(NOT KERNEL_NAME OR NOT KERNEL_MANIFEST_PATH) message(FATAL_ERROR "rust_kernel_component: NAME and MANIFEST_PATH are required") @@ -10,6 +10,62 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) "but `cargo` was not found. Install a Rust toolchain or set CARGO_EXECUTABLE.") endif() + if(GPU_LANG STREQUAL "CUDA") + if(KERNEL_CUDA_CAPABILITIES) + cuda_archs_intersection(_KERNEL_ARCHS "${KERNEL_CUDA_CAPABILITIES}" "${CUDA_ARCHS}") + if(NOT _KERNEL_ARCHS) + message(FATAL_ERROR "Rust kernel: ${KERNEL_NAME}, empty set of capabilities after intersection (kernel: ${KERNEL_CUDA_CAPABILITIES}, supported: ${CUDA_ARCHS})") + endif() + else() + set(_KERNEL_ARCHS "${CUDA_KERNEL_ARCHS}") + endif() + message(STATUS "Rust kernel: ${KERNEL_NAME}, capabilities: ${_KERNEL_ARCHS}") + + accumulate_gpu_archs(_ALL_GPU_ARCHS "${ALL_GPU_ARCHS}" "${_KERNEL_ARCHS}") + set(ALL_GPU_ARCHS ${_ALL_GPU_ARCHS} PARENT_SCOPE) + endif() + + set(_RUST_KERNEL_DEPENDS) + + if(KERNEL_DEVICE_MANIFEST) + # Build cuda-oxide device code before the host crate embeds its PTX. + if(NOT DEFINED ENV{CUDA_OXIDE_BACKEND} OR "$ENV{CUDA_OXIDE_BACKEND}" STREQUAL "") + message(FATAL_ERROR "rust_kernel_component: DEVICE_MANIFEST requires CUDA_OXIDE_BACKEND") + endif() + if(NOT KERNEL_PTX_DIR) + set(KERNEL_PTX_DIR kernels-ptx) + endif() + + get_filename_component(_DEVICE_MANIFEST ${KERNEL_DEVICE_MANIFEST} ABSOLUTE BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) + get_filename_component(_PTX_DIR ${KERNEL_PTX_DIR} ABSOLUTE BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) + set(_DEVICE_TARGET_DIR ${CMAKE_BINARY_DIR}/cargo/${KERNEL_NAME}-device) + set(_DEVICE_ENV) + + if(_KERNEL_ARCHS) + list(SORT _KERNEL_ARCHS COMPARE NATURAL) + # PTX JITs forward, so target the lowest supported arch. + list(GET _KERNEL_ARCHS 0 _OXIDE_ARCH) + string(REPLACE "+PTX" "" _OXIDE_ARCH "${_OXIDE_ARCH}") + string(REPLACE "." "" _OXIDE_ARCH "${_OXIDE_ARCH}") + list(APPEND _DEVICE_ENV "CUDA_OXIDE_TARGET=sm_${_OXIDE_ARCH}") + endif() + + add_custom_target(${KERNEL_NAME}_oxide_device_build ALL + COMMAND ${CMAKE_COMMAND} -E make_directory ${_PTX_DIR} + COMMAND ${CMAKE_COMMAND} -E env + "CUDA_OXIDE_PTX_DIR=${_PTX_DIR}" + "RUSTFLAGS=-Zcodegen-backend=$ENV{CUDA_OXIDE_BACKEND} -Copt-level=3 -Cdebug-assertions=off -Zmir-enable-passes=-JumpThreading -Csymbol-mangling-version=v0" + ${_DEVICE_ENV} + ${CARGO_EXECUTABLE} build --release --locked + --manifest-path ${_DEVICE_MANIFEST} + --target-dir ${_DEVICE_TARGET_DIR} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + COMMENT "Building Rust CUDA device kernel ${KERNEL_NAME}" + VERBATIM + ) + list(APPEND _RUST_KERNEL_DEPENDS ${KERNEL_NAME}_oxide_device_build) + endif() + string(REPLACE "-" "_" _LIB_NAME ${KERNEL_NAME}) set(_CARGO_TARGET_DIR ${CMAKE_BINARY_DIR}/cargo/${KERNEL_NAME}) @@ -21,9 +77,12 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) add_custom_target(${KERNEL_NAME}_cargo_build ALL COMMAND ${CMAKE_COMMAND} -E env "PATH=${_PYTHON_BIN_DIR}:$ENV{PATH}" + "KERNEL_BUILDER_GPU_LANG=${GPU_LANG}" + "KERNEL_BUILDER_CUDA_ARCHS=${_KERNEL_ARCHS}" ${CARGO_EXECUTABLE} rustc --release --locked --lib --crate-type staticlib --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH} --target-dir ${_CARGO_TARGET_DIR} + DEPENDS ${_RUST_KERNEL_DEPENDS} BYPRODUCTS ${_STATICLIB} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Building Rust kernel ${KERNEL_NAME} with cargo" @@ -82,5 +141,10 @@ function(target_link_rust_kernels TARGET) "$" Threads::Threads ${CMAKE_DL_LIBS}) + # Cargo's native-library link directives do not propagate out of a staticlib. + if(GPU_LANG STREQUAL "CUDA") + find_package(CUDAToolkit REQUIRED) + target_link_libraries(${TARGET} PRIVATE CUDA::cuda_driver) + endif() _restrict_rust_exports(${TARGET}) endfunction() diff --git a/kernel-builder/tests/rust-components.cmake b/kernel-builder/tests/rust-components.cmake new file mode 100644 index 00000000..72cf2dc8 --- /dev/null +++ b/kernel-builder/tests/rust-components.cmake @@ -0,0 +1,60 @@ +# Configure Rust targets without CUDA or compiling crates. +# Run: cmake -P kernel-builder/tests/rust-components.cmake +cmake_minimum_required(VERSION 3.24) +if(CMAKE_SCRIPT_MODE_FILE) + set(_TEST_DIR "${CMAKE_CURRENT_BINARY_DIR}/rust-components-test") + file(MAKE_DIRECTORY "${_TEST_DIR}") + file(WRITE "${_TEST_DIR}/CMakeLists.txt" + "cmake_minimum_required(VERSION 3.24)\nproject(rust_components NONE)\ninclude(\"${CMAKE_CURRENT_LIST_FILE}\")\n") + foreach(_CASE cpu cuda host-only unsupported-arch missing-backend) + execute_process(COMMAND "${CMAKE_COMMAND}" -S "${_TEST_DIR}" + -G Ninja -B "${_TEST_DIR}/${_CASE}" "-DCASE=${_CASE}" + RESULT_VARIABLE _RESULT OUTPUT_VARIABLE _OUTPUT ERROR_VARIABLE _ERROR) + if(_CASE STREQUAL "unsupported-arch") + if(_RESULT EQUAL 0 OR NOT _ERROR MATCHES "empty set of capabilities") + message(FATAL_ERROR "Expected unsupported architecture error: ${_OUTPUT}${_ERROR}") + endif() + elseif(_CASE STREQUAL "missing-backend") + if(_RESULT EQUAL 0 OR NOT _ERROR MATCHES "requires CUDA_OXIDE_BACKEND") + message(FATAL_ERROR "Expected missing backend error: ${_OUTPUT}${_ERROR}") + endif() + elseif(NOT _RESULT EQUAL 0) + message(FATAL_ERROR "${_CASE} configuration failed: ${_OUTPUT}${_ERROR}") + endif() + endforeach() + file(REMOVE_RECURSE "${_TEST_DIR}") + message(STATUS "Rust component configuration tests passed") + return() +endif() + +include("${CMAKE_CURRENT_LIST_DIR}/../src/pyproject/templates/utils.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/../src/pyproject/templates/kernel.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/../src/pyproject/templates/rust.cmake") +set(CARGO_EXECUTABLE cargo) +set(Python_EXECUTABLE python) +set(GPU_LANG CUDA) +set(CUDA_ARCHS "8.0;8.9;9.0") +set(CUDA_KERNEL_ARCHS "8.0;8.9;9.0+PTX") +set(ENV{CUDA_OXIDE_BACKEND} /test/backend.so) +set(_ARGS CUDA_CAPABILITIES 8.0 DEVICE_MANIFEST device/Cargo.toml) +if(CASE STREQUAL "cpu") + set(GPU_LANG CPU) + set(_ARGS) +elseif(CASE STREQUAL "host-only") + set(_ARGS) +elseif(CASE STREQUAL "unsupported-arch") + set(_ARGS CUDA_CAPABILITIES 6.0 DEVICE_MANIFEST device/Cargo.toml) +elseif(CASE STREQUAL "missing-backend") + unset(ENV{CUDA_OXIDE_BACKEND}) +endif() +rust_kernel_component(LIBS TARGETS NAME example MANIFEST_PATH Cargo.toml ${_ARGS}) +if(NOT TARGET example_rust OR NOT TARGET example_cargo_build) + message(FATAL_ERROR "Missing shared Cargo/static-library targets") +endif() +if(CASE STREQUAL "cuda") + if(NOT TARGET example_oxide_device_build OR NOT ALL_GPU_ARCHS STREQUAL "8.0") + message(FATAL_ERROR "Missing device target or incorrect capabilities") + endif() +elseif(TARGET example_oxide_device_build) + message(FATAL_ERROR "Unexpected device build for ${CASE}") +endif() diff --git a/kernels-common/src/config/mod.rs b/kernels-common/src/config/mod.rs index fb1de026..e566dd65 100644 --- a/kernels-common/src/config/mod.rs +++ b/kernels-common/src/config/mod.rs @@ -356,6 +356,15 @@ pub enum Kernel { depends: Vec, src: Vec, }, + + RustCuda { + cargo_manifest: String, + device_manifest: Option, + ptx_dir: Option, + cuda_capabilities: Option>, + depends: Vec, + src: Vec, + }, CppCuda { cuda_capabilities: Option>, cuda_flags: Option>, @@ -396,7 +405,7 @@ impl Kernel { | Kernel::CppMetal { cxx_flags, .. } | Kernel::CppRocm { cxx_flags, .. } | Kernel::CppXpu { cxx_flags, .. } => cxx_flags.as_deref(), - Kernel::RustCpu { .. } => None, + Kernel::RustCpu { .. } | Kernel::RustCuda { .. } => None, } } @@ -407,7 +416,7 @@ impl Kernel { | Kernel::CppMetal { include, .. } | Kernel::CppRocm { include, .. } | Kernel::CppXpu { include, .. } => include.as_deref(), - Kernel::RustCpu { .. } => None, + Kernel::RustCpu { .. } | Kernel::RustCuda { .. } => None, } } @@ -421,7 +430,7 @@ impl Kernel { pub fn backend(&self) -> Backend { match self { Kernel::CppCpu { .. } | Kernel::RustCpu { .. } => Backend::Cpu, - Kernel::CppCuda { .. } => Backend::Cuda, + Kernel::CppCuda { .. } | Kernel::RustCuda { .. } => Backend::Cuda, Kernel::CppMetal { .. } => Backend::Metal, Kernel::CppRocm { .. } => Backend::Rocm, Kernel::CppXpu { .. } => Backend::Xpu, @@ -435,7 +444,7 @@ impl Kernel { | Kernel::CppMetal { .. } | Kernel::CppRocm { .. } | Kernel::CppXpu { .. } => Language::Cpp, - Kernel::RustCpu { .. } => Language::Rust, + Kernel::RustCpu { .. } | Kernel::RustCuda { .. } => Language::Rust, } } @@ -443,6 +452,7 @@ impl Kernel { match self { Kernel::CppCpu { depends, .. } | Kernel::RustCpu { depends, .. } + | Kernel::RustCuda { depends, .. } | Kernel::CppCuda { depends, .. } | Kernel::CppMetal { depends, .. } | Kernel::CppRocm { depends, .. } @@ -454,6 +464,7 @@ impl Kernel { match self { Kernel::CppCpu { src, .. } | Kernel::RustCpu { src, .. } + | Kernel::RustCuda { src, .. } | Kernel::CppCuda { src, .. } | Kernel::CppMetal { src, .. } | Kernel::CppRocm { src, .. } @@ -735,9 +746,65 @@ mod tests { assert_eq!(build.kernels["cpu_kernel"].language(), Language::Rust); } + #[test] + fn v6_rust_cuda_round_trip() { + let config = r#" + [general] + name = "rust-cuda" + version = 1 + edition = 6 + license = "Apache-2.0" + backends = ["cuda"] + [tvm-ffi] + [kernel.gpu_kernel] + language = "rust-cuda" + cargo-manifest = "host/Cargo.toml" + device-manifest = "device/Cargo.toml" + ptx-dir = "ptx" + cuda-capabilities = ["8.0"] + depends = [] + src = ["host/src", "device/src"] + "#; + let build = Build::try_from(toml::from_str::(config).unwrap()).unwrap(); + assert_eq!(build.kernels["gpu_kernel"].language(), Language::Rust); + assert_eq!(build.kernels["gpu_kernel"].backend(), Backend::Cuda); + let serialized = toml::to_string(&v6::Build::from(build)).unwrap(); + let reparsed: v6::Build = toml::from_str(&serialized).unwrap(); + match &reparsed.kernels["gpu_kernel"] { + v6::Kernel::RustCuda { + cargo_manifest, + device_manifest, + ptx_dir, + cuda_capabilities, + .. + } => { + assert_eq!(cargo_manifest, "host/Cargo.toml"); + assert_eq!(device_manifest.as_deref(), Some("device/Cargo.toml")); + assert_eq!(ptx_dir.as_deref(), Some("ptx")); + assert_eq!( + cuda_capabilities.as_deref(), + Some(["8.0".to_string()].as_slice()) + ); + } + _ => panic!("expected Rust CUDA kernel"), + } + } + #[test] fn v6_rust_kernel_rejects_invalid_config() { let cases = [ + ( + "[torch]\nsrc = []", + "rust-cuda", + "", + "require a `[tvm-ffi]` framework", + ), + ( + "[tvm-ffi]", + "rust-cuda", + r#"cuda-flags = ["-O3"]"#, + "unknown field `cuda-flags`", + ), ( "[tvm-ffi]", "rust-cpu", diff --git a/kernels-common/src/config/v6.rs b/kernels-common/src/config/v6.rs index c4f621f4..b924640d 100644 --- a/kernels-common/src/config/v6.rs +++ b/kernels-common/src/config/v6.rs @@ -166,6 +166,16 @@ pub enum Kernel { depends: Vec, src: Vec, }, + + #[serde(rename_all = "kebab-case")] + RustCuda { + cargo_manifest: String, + device_manifest: Option, + ptx_dir: Option, + cuda_capabilities: Option>, + depends: Vec, + src: Vec, + }, #[serde(rename_all = "kebab-case")] CppCuda { cuda_capabilities: Option>, @@ -224,10 +234,12 @@ impl TryFrom for super::Build { .kernels .into_iter() .map(|(name, kernel)| match kernel { - Kernel::RustCpu { .. } if !tvm_ffi => Err(ConfigError::InvalidKernel { - name, - reason: "Rust kernels require a `[tvm-ffi]` framework".into(), - }), + Kernel::RustCpu { .. } | Kernel::RustCuda { .. } if !tvm_ffi => { + Err(ConfigError::InvalidKernel { + name, + reason: "Rust kernels require a `[tvm-ffi]` framework".into(), + }) + } kernel => Ok((name, kernel.into())), }) .collect::>()?; @@ -382,6 +394,22 @@ impl From for super::Kernel { include, src, }, + + Kernel::RustCuda { + cargo_manifest, + device_manifest, + ptx_dir, + cuda_capabilities, + depends, + src, + } => super::Kernel::RustCuda { + cargo_manifest, + device_manifest, + ptx_dir, + cuda_capabilities, + depends, + src, + }, Kernel::RustCpu { cargo_manifest, depends, @@ -617,6 +645,22 @@ impl From for Kernel { depends, src, }, + + super::Kernel::RustCuda { + cargo_manifest, + device_manifest, + ptx_dir, + cuda_capabilities, + depends, + src, + } => Kernel::RustCuda { + cargo_manifest, + device_manifest, + ptx_dir, + cuda_capabilities, + depends, + src, + }, super::Kernel::CppCuda { cuda_capabilities, cuda_flags, diff --git a/nix-builder/lib/build.nix b/nix-builder/lib/build.nix index a43fd6ca..025c3fbf 100644 --- a/nix-builder/lib/build.nix +++ b/nix-builder/lib/build.nix @@ -202,6 +202,9 @@ rec { kernelProvenance ; + rustCudaDevice = lib.any (kernel: kernel.language == "rust-cuda" && kernel ? device-manifest) ( + lib.attrValues kernels + ); cargoLock = if hasRustKernels then src + "/Cargo.lock" else null; rustGitHashes = if hasRustKernels && builtins.pathExists (src + "/rust-git-hashes.json") then diff --git a/nix-builder/lib/extension/tvm-ffi/arch.nix b/nix-builder/lib/extension/tvm-ffi/arch.nix index f3cec3c7..6ffccf2b 100644 --- a/nix-builder/lib/extension/tvm-ffi/arch.nix +++ b/nix-builder/lib/extension/tvm-ffi/arch.nix @@ -62,6 +62,9 @@ # the build has no Rust kernels. cargoLock ? null, + # Compile CUDA device crates with cuda-oxide and its matching rustc. + rustCudaDevice ? false, + # Fixed-output hashes for Git dependencies in Cargo.lock. rustGitHashes ? { }, @@ -136,31 +139,45 @@ let metalSupport = buildConfig.metal or false; rustSupport = cargoLock != null; + rustCuda = import ./rust-cuda.nix { + inherit + pkgs + lib + stdenv + cudaPackages + ; + }; # rpaths are stripped from kernels to make them portable, but that # also means that in a Nix environment the CUDA/ROCm/oneAPI dependencies # cannot be located anymore, so pass them to hooks that load the kernel. - libraryPath = lib.makeLibraryPath ( - map lib.getLib ( - lib.optionals cudaSupport ( - with cudaPackages; - [ - cuda_cudart - libcublas - libcusolver - libcusparse - ] - ) - ++ lib.optionals rocmSupport [ clr ] - ++ lib.optionals xpuSupport ( - with xpuPackages; - [ - intel-oneapi-compiler-dpcpp-cpp-runtime - intel-oneapi-compiler-shared-runtime - ] + libraryPath = + lib.makeLibraryPath ( + map lib.getLib ( + lib.optionals cudaSupport ( + with cudaPackages; + [ + cuda_cudart + libcublas + libcusolver + libcusparse + ] + ) + ++ lib.optionals rocmSupport [ clr ] + ++ lib.optionals xpuSupport ( + with xpuPackages; + [ + intel-oneapi-compiler-dpcpp-cpp-runtime + intel-oneapi-compiler-shared-runtime + ] + ) ) ) - ); + + + lib.optionalString (rustSupport && cudaSupport) + # Import checks run without a GPU driver in the build sandbox. The stub is + # only used by the check hooks, never bundled in the redistributable kernel. + ":${lib.getOutput "stubs" cudaPackages.cuda_cudart}/lib/stubs"; provenanceFlags = import ../provenance-flags.nix { inherit lib kernelProvenance; }; @@ -253,9 +270,12 @@ stdenv.mkDerivation ( ] ++ lib.optionals rustSupport [ rustPlatform.cargoSetupHook + ] + ++ lib.optionals (rustSupport && !rustCudaDevice) [ cargo rustc - ]; + ] + ++ lib.optionals rustCudaDevice [ rustCuda.toolchain ]; buildInputs = [ python3.pkgs.tvm-ffi @@ -305,6 +325,10 @@ stdenv.mkDerivation ( // lib.optionalAttrs cudaSupport { CUDAToolkit_ROOT = "${lib.getDev cudaPackages.cuda_nvcc}"; } + // lib.optionalAttrs (rustSupport && cudaSupport) rustCuda.env + // lib.optionalAttrs rustCudaDevice { + CUDA_OXIDE_BACKEND = "${rustCuda.backend}/lib/librustc_codegen_cuda.so"; + } // lib.optionalAttrs xpuSupport { MKLROOT = oneapi-torch-dev; SYCL_ROOT = oneapi-torch-dev; @@ -335,6 +359,12 @@ stdenv.mkDerivation ( # rpaths anyway. (lib.cmakeBool "CMAKE_SKIP_RPATH" true) ] + # Rust toolchains can propagate a newer compiler onto PATH. Link with the + # selected stdenv so redistributable kernels retain their glibc baseline. + ++ lib.optionals rustSupport [ + (lib.cmakeFeature "CMAKE_C_COMPILER" "${stdenv.cc}/bin/cc") + (lib.cmakeFeature "CMAKE_CXX_COMPILER" "${stdenv.cc}/bin/c++") + ] ++ lib.optionals cudaSupport [ (lib.cmakeFeature "CMAKE_CUDA_HOST_COMPILER" "${stdenv.cc}/bin/g++") (lib.cmakeFeature "GPU_LANG" "CUDA") diff --git a/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix b/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix new file mode 100644 index 00000000..cbb20d56 --- /dev/null +++ b/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix @@ -0,0 +1,60 @@ +# cuda-oxide is a rustc codegen plugin and must use its matching Rust toolchain. +{ + pkgs, + lib, + stdenv, + cudaPackages, +}: +let + src = pkgs.fetchFromGitHub { + owner = "NVIDIA"; + repo = "cuda-rust"; + rev = "6d47ae49cb256a07948fb499c20c3eb9b2a96268"; + hash = "sha256-g9qg2zHLybO8kPLoOJqnYbWjRYtjGV3QVT+X4f8+1fg="; + }; + toolchain = pkgs.rust-bin.fromRustupToolchainFile "${src}/cuda-oxide/rust-toolchain.toml"; + platform = pkgs.makeRustPlatform { + cargo = toolchain; + rustc = toolchain; + }; + backend = platform.buildRustPackage { + pname = "rustc-codegen-cuda"; + version = "0.2.1"; + inherit src; + sourceRoot = "source/cuda-oxide/crates/rustc-codegen-cuda"; + cargoLock = { + lockFile = "${src}/cuda-oxide/crates/rustc-codegen-cuda/Cargo.lock"; + outputHashes."pliron-0.18.0" = "sha256-HQ/xNfQcIf9pQRrgxCYGFdVfdCMaE4iwj/G9mgAJOWw="; + }; + buildInputs = with pkgs; [ + libffi + libxml2 + zstd + zlib + ]; + doCheck = false; + }; + cudaHome = pkgs.symlinkJoin { + name = "cuda-home"; + paths = with cudaPackages; [ + (lib.getDev cuda_cudart) + (lib.getLib cuda_cudart) + (lib.getDev cccl) + (lib.getOutput "include" libcurand) + cuda_crt + ]; + }; +in +{ + inherit toolchain backend; + env = { + CUDA_HOME = cudaHome; + CUDA_TOOLKIT_PATH = cudaHome; + LIBRARY_PATH = "${lib.getOutput "stubs" cudaPackages.cuda_cudart}/lib/stubs"; + LIBCLANG_PATH = "${lib.getLib pkgs.libclang}/lib"; + BINDGEN_EXTRA_CLANG_ARGS = lib.concatStringsSep " " [ + "-isystem ${lib.getLib pkgs.libclang}/lib/clang/${lib.versions.major pkgs.libclang.version}/include" + "-isystem ${lib.getDev stdenv.cc.libc}/include" + ]; + }; +} diff --git a/nix-builder/lib/source-set.nix b/nix-builder/lib/source-set.nix index a1d75909..36276b75 100644 --- a/nix-builder/lib/source-set.nix +++ b/nix-builder/lib/source-set.nix @@ -43,7 +43,11 @@ let else fileset.empty; # Rust kernels also need their Cargo manifest. - kernelSrc = kernel: kernel.src ++ lib.optional (kernel ? cargo-manifest) kernel.cargo-manifest; + kernelSrc = + kernel: + kernel.src + ++ lib.optional (kernel ? cargo-manifest) kernel.cargo-manifest + ++ lib.optional (kernel ? device-manifest) kernel.device-manifest; kernelsSrc = fileset.unions ( lib.flatten (lib.mapAttrsToList (name: kernel: map (nameToPath path) (kernelSrc kernel)) kernels) ); @@ -55,6 +59,7 @@ fileset.toSource { kernelsSrc lockSet cargoLockSet + (fileset.maybeMissing (path + "/rust-toolchain.toml")) rustGitHashesSet srcSet pySrcSet From 9cd4c01cfa7bec0174e368541381aa93530b8c32 Mon Sep 17 00:00:00 2001 From: David Holtz Date: Tue, 20 Oct 2026 19:44:28 +0000 Subject: [PATCH 2/5] feat: simplify rust cuda build and drop extra env vars --- kernel-builder/src/pyproject/kernel.rs | 35 ++----- .../kernel-component/rust-cuda.cmake | 2 - .../src/pyproject/templates/rust.cmake | 95 ++++++++++++++----- kernel-builder/tests/rust-components.cmake | 24 +++-- kernels-common/src/config/mod.rs | 42 +++----- kernels-common/src/config/v6.rs | 13 --- nix-builder/lib/build.nix | 3 - nix-builder/lib/extension/tvm-ffi/arch.nix | 68 +++++-------- .../lib/extension/tvm-ffi/rust-cuda.nix | 27 +----- nix-builder/lib/source-set.nix | 6 +- 10 files changed, 136 insertions(+), 179 deletions(-) diff --git a/kernel-builder/src/pyproject/kernel.rs b/kernel-builder/src/pyproject/kernel.rs index aa603f92..7ccfe5a7 100644 --- a/kernel-builder/src/pyproject/kernel.rs +++ b/kernel-builder/src/pyproject/kernel.rs @@ -42,8 +42,6 @@ fn render_kernel_component( } Kernel::RustCuda { cargo_manifest, - device_manifest, - ptx_dir, cuda_capabilities, .. } => { @@ -52,8 +50,6 @@ fn render_kernel_component( context! { name => kernel_name, manifest_path => cargo_manifest, - device_manifest => device_manifest, - ptx_dir => ptx_dir, cuda_capabilities => cuda_capabilities, }, &mut *write, @@ -267,7 +263,7 @@ mod tests { fn rust_components_render_for_their_backend() { let mut env = Environment::new(); minijinja_embed::load_templates!(&mut env); - for (kernel, backend, device) in [ + for (kernel, backend, capabilities) in [ ( Kernel::RustCpu { cargo_manifest: "host/Cargo.toml".into(), @@ -275,31 +271,17 @@ mod tests { src: vec![], }, "CPU", - false, + None, ), ( Kernel::RustCuda { cargo_manifest: "host/Cargo.toml".into(), - device_manifest: Some("device/Cargo.toml".into()), - ptx_dir: Some("ptx".into()), cuda_capabilities: Some(vec!["8.0".into(), "9.0".into()]), depends: vec![], src: vec![], }, "CUDA", - true, - ), - ( - Kernel::RustCuda { - cargo_manifest: "host/Cargo.toml".into(), - device_manifest: None, - ptx_dir: None, - cuda_capabilities: None, - depends: vec![], - src: vec![], - }, - "CUDA", - false, + Some("CUDA_CAPABILITIES 8.0 9.0"), ), ] { let mut rendered = vec![]; @@ -307,11 +289,12 @@ mod tests { let rendered = String::from_utf8(rendered).unwrap(); assert!(rendered.contains(&format!("if(GPU_LANG STREQUAL \"{backend}\")"))); assert!(rendered.contains("MANIFEST_PATH \"host/Cargo.toml\"")); - assert_eq!(rendered.contains("DEVICE_MANIFEST"), device); - if device { - assert!(rendered.contains("DEVICE_MANIFEST \"device/Cargo.toml\"")); - assert!(rendered.contains("PTX_DIR \"ptx\"")); - assert!(rendered.contains("CUDA_CAPABILITIES 8.0 9.0")); + assert_eq!( + rendered.contains("CUDA_CAPABILITIES"), + capabilities.is_some() + ); + if let Some(capabilities) = capabilities { + assert!(rendered.contains(capabilities)); } } } diff --git a/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake b/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake index 7664b3cf..83ff7ba3 100644 --- a/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake +++ b/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake @@ -2,8 +2,6 @@ if(GPU_LANG STREQUAL "CUDA") rust_kernel_component(RUST_KERNEL_LIBS RUST_KERNEL_TARGETS NAME {{ name }} MANIFEST_PATH "{{ manifest_path }}" - {% if device_manifest %}DEVICE_MANIFEST "{{ device_manifest }}"{% endif %} - {% if ptx_dir %}PTX_DIR "{{ ptx_dir }}"{% endif %} {% if cuda_capabilities %}CUDA_CAPABILITIES {{ cuda_capabilities | join(" ") }}{% endif %} ) endif() diff --git a/kernel-builder/src/pyproject/templates/rust.cmake b/kernel-builder/src/pyproject/templates/rust.cmake index 1c2a056b..1b791f06 100644 --- a/kernel-builder/src/pyproject/templates/rust.cmake +++ b/kernel-builder/src/pyproject/templates/rust.cmake @@ -1,5 +1,47 @@ +# cuda-oxide interop: device crates are declared by the host crate in +# `[[package.metadata.cuda-oxide.device-crates]]`, as `cargo oxide` reads them. +function(_cuda_oxide_device_manifests OUT_VAR MANIFEST) + execute_process( + COMMAND ${CARGO_EXECUTABLE} metadata --format-version 1 --no-deps --offline + --manifest-path ${MANIFEST} + OUTPUT_VARIABLE _JSON + ERROR_VARIABLE _ERROR + RESULT_VARIABLE _RESULT) + if(NOT _RESULT EQUAL 0) + message(FATAL_ERROR "cargo metadata failed for ${MANIFEST}: ${_ERROR}") + endif() + + file(REAL_PATH ${MANIFEST} _MANIFEST) + set(_MANIFESTS) + string(JSON _N_PACKAGES LENGTH "${_JSON}" packages) + math(EXPR _LAST_PACKAGE "${_N_PACKAGES} - 1") + foreach(_I RANGE ${_LAST_PACKAGE}) + string(JSON _PACKAGE_MANIFEST GET "${_JSON}" packages ${_I} manifest_path) + file(REAL_PATH ${_PACKAGE_MANIFEST} _PACKAGE_MANIFEST) + if(NOT _PACKAGE_MANIFEST STREQUAL _MANIFEST) + continue() + endif() + + string(JSON _CRATES ERROR_VARIABLE _NO_CRATES + GET "${_JSON}" packages ${_I} metadata cuda-oxide device-crates) + if(_NO_CRATES) + break() + endif() + get_filename_component(_PACKAGE_DIR ${_PACKAGE_MANIFEST} DIRECTORY) + string(JSON _N_CRATES LENGTH "${_CRATES}") + math(EXPR _LAST_CRATE "${_N_CRATES} - 1") + foreach(_J RANGE ${_LAST_CRATE}) + string(JSON _CRATE_MANIFEST GET "${_CRATES}" ${_J} manifest-path) + get_filename_component(_CRATE_MANIFEST ${_CRATE_MANIFEST} ABSOLUTE BASE_DIR ${_PACKAGE_DIR}) + list(APPEND _MANIFESTS ${_CRATE_MANIFEST}) + endforeach() + endforeach() + + set(${OUT_VAR} ${_MANIFESTS} PARENT_SCOPE) +endfunction() + function(rust_kernel_component LIBS_VAR TARGETS_VAR) - cmake_parse_arguments(KERNEL "" "NAME;MANIFEST_PATH;DEVICE_MANIFEST;PTX_DIR" "CUDA_CAPABILITIES" ${ARGN}) + cmake_parse_arguments(KERNEL "" "NAME;MANIFEST_PATH" "CUDA_CAPABILITIES" ${ARGN}) if(NOT KERNEL_NAME OR NOT KERNEL_MANIFEST_PATH) message(FATAL_ERROR "rust_kernel_component: NAME and MANIFEST_PATH are required") @@ -25,20 +67,20 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) set(ALL_GPU_ARCHS ${_ALL_GPU_ARCHS} PARENT_SCOPE) endif() - set(_RUST_KERNEL_DEPENDS) + set(_HOST_ENV) + if(GPU_LANG STREQUAL "CUDA") + _cuda_oxide_device_manifests(_DEVICE_MANIFESTS + ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH}) + endif() - if(KERNEL_DEVICE_MANIFEST) + if(_DEVICE_MANIFESTS) # Build cuda-oxide device code before the host crate embeds its PTX. - if(NOT DEFINED ENV{CUDA_OXIDE_BACKEND} OR "$ENV{CUDA_OXIDE_BACKEND}" STREQUAL "") - message(FATAL_ERROR "rust_kernel_component: DEVICE_MANIFEST requires CUDA_OXIDE_BACKEND") - endif() - if(NOT KERNEL_PTX_DIR) - set(KERNEL_PTX_DIR kernels-ptx) + if(NOT CUDA_OXIDE_BACKEND) + message(FATAL_ERROR "rust_kernel_component: cuda-oxide device crates require CUDA_OXIDE_BACKEND") endif() - get_filename_component(_DEVICE_MANIFEST ${KERNEL_DEVICE_MANIFEST} ABSOLUTE BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) - get_filename_component(_PTX_DIR ${KERNEL_PTX_DIR} ABSOLUTE BASE_DIR ${CMAKE_CURRENT_SOURCE_DIR}) set(_DEVICE_TARGET_DIR ${CMAKE_BINARY_DIR}/cargo/${KERNEL_NAME}-device) + set(_PTX_DIR ${_DEVICE_TARGET_DIR}/ptx) set(_DEVICE_ENV) if(_KERNEL_ARCHS) @@ -50,20 +92,27 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) list(APPEND _DEVICE_ENV "CUDA_OXIDE_TARGET=sm_${_OXIDE_ARCH}") endif() + set(_DEVICE_COMMANDS) + foreach(_DEVICE_MANIFEST ${_DEVICE_MANIFESTS}) + # Flags match what `cargo oxide build` passes to the codegen backend. + list(APPEND _DEVICE_COMMANDS + COMMAND ${CMAKE_COMMAND} -E env + "CUDA_OXIDE_PTX_DIR=${_PTX_DIR}" + "RUSTFLAGS=-Zcodegen-backend=${CUDA_OXIDE_BACKEND} -Copt-level=3 -Cdebug-assertions=off -Zmir-enable-passes=-JumpThreading -Csymbol-mangling-version=v0" + ${_DEVICE_ENV} + ${CARGO_EXECUTABLE} build --release --locked + --manifest-path ${_DEVICE_MANIFEST} + --target-dir ${_DEVICE_TARGET_DIR}) + endforeach() + add_custom_target(${KERNEL_NAME}_oxide_device_build ALL COMMAND ${CMAKE_COMMAND} -E make_directory ${_PTX_DIR} - COMMAND ${CMAKE_COMMAND} -E env - "CUDA_OXIDE_PTX_DIR=${_PTX_DIR}" - "RUSTFLAGS=-Zcodegen-backend=$ENV{CUDA_OXIDE_BACKEND} -Copt-level=3 -Cdebug-assertions=off -Zmir-enable-passes=-JumpThreading -Csymbol-mangling-version=v0" - ${_DEVICE_ENV} - ${CARGO_EXECUTABLE} build --release --locked - --manifest-path ${_DEVICE_MANIFEST} - --target-dir ${_DEVICE_TARGET_DIR} + ${_DEVICE_COMMANDS} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Building Rust CUDA device kernel ${KERNEL_NAME}" VERBATIM ) - list(APPEND _RUST_KERNEL_DEPENDS ${KERNEL_NAME}_oxide_device_build) + list(APPEND _HOST_ENV "KERNEL_BUILDER_PTX_DIR=${_PTX_DIR}") endif() string(REPLACE "-" "_" _LIB_NAME ${KERNEL_NAME}) @@ -79,15 +128,18 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) COMMAND ${CMAKE_COMMAND} -E env "PATH=${_PYTHON_BIN_DIR}:$ENV{PATH}" "KERNEL_BUILDER_GPU_LANG=${GPU_LANG}" "KERNEL_BUILDER_CUDA_ARCHS=${_KERNEL_ARCHS}" + ${_HOST_ENV} ${CARGO_EXECUTABLE} rustc --release --locked --lib --crate-type staticlib --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH} --target-dir ${_CARGO_TARGET_DIR} - DEPENDS ${_RUST_KERNEL_DEPENDS} BYPRODUCTS ${_STATICLIB} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Building Rust kernel ${KERNEL_NAME} with cargo" VERBATIM ) + if(_DEVICE_MANIFESTS) + add_dependencies(${KERNEL_NAME}_cargo_build ${KERNEL_NAME}_oxide_device_build) + endif() add_library(${KERNEL_NAME}_rust STATIC IMPORTED GLOBAL) set_target_properties(${KERNEL_NAME}_rust PROPERTIES IMPORTED_LOCATION ${_STATICLIB}) @@ -141,10 +193,5 @@ function(target_link_rust_kernels TARGET) "$" Threads::Threads ${CMAKE_DL_LIBS}) - # Cargo's native-library link directives do not propagate out of a staticlib. - if(GPU_LANG STREQUAL "CUDA") - find_package(CUDAToolkit REQUIRED) - target_link_libraries(${TARGET} PRIVATE CUDA::cuda_driver) - endif() _restrict_rust_exports(${TARGET}) endfunction() diff --git a/kernel-builder/tests/rust-components.cmake b/kernel-builder/tests/rust-components.cmake index 72cf2dc8..6b435009 100644 --- a/kernel-builder/tests/rust-components.cmake +++ b/kernel-builder/tests/rust-components.cmake @@ -1,11 +1,17 @@ -# Configure Rust targets without CUDA or compiling crates. -# Run: cmake -P kernel-builder/tests/rust-components.cmake +# Configure Rust targets without CUDA or compiling crates (needs `cargo` for +# `cargo metadata`). Run: cmake -P kernel-builder/tests/rust-components.cmake cmake_minimum_required(VERSION 3.24) if(CMAKE_SCRIPT_MODE_FILE) set(_TEST_DIR "${CMAKE_CURRENT_BINARY_DIR}/rust-components-test") file(MAKE_DIRECTORY "${_TEST_DIR}") file(WRITE "${_TEST_DIR}/CMakeLists.txt" "cmake_minimum_required(VERSION 3.24)\nproject(rust_components NONE)\ninclude(\"${CMAKE_CURRENT_LIST_FILE}\")\n") + # Host crates with and without cuda-oxide device crates. + set(_PACKAGE "[package]\nname = \"example\"\nversion = \"0.0.0\"\nedition = \"2021\"\n[lib]\npath = \"lib.rs\"\n[workspace]\n") + file(WRITE "${_TEST_DIR}/plain/Cargo.toml" "${_PACKAGE}") + file(WRITE "${_TEST_DIR}/oxide/Cargo.toml" "${_PACKAGE}" + "[[package.metadata.cuda-oxide.device-crates]]\nmanifest-path = \"device/Cargo.toml\"\n") + file(TOUCH "${_TEST_DIR}/plain/lib.rs" "${_TEST_DIR}/oxide/lib.rs") foreach(_CASE cpu cuda host-only unsupported-arch missing-backend) execute_process(COMMAND "${CMAKE_COMMAND}" -S "${_TEST_DIR}" -G Ninja -B "${_TEST_DIR}/${_CASE}" "-DCASE=${_CASE}" @@ -15,7 +21,7 @@ if(CMAKE_SCRIPT_MODE_FILE) message(FATAL_ERROR "Expected unsupported architecture error: ${_OUTPUT}${_ERROR}") endif() elseif(_CASE STREQUAL "missing-backend") - if(_RESULT EQUAL 0 OR NOT _ERROR MATCHES "requires CUDA_OXIDE_BACKEND") + if(_RESULT EQUAL 0 OR NOT _ERROR MATCHES "require CUDA_OXIDE_BACKEND") message(FATAL_ERROR "Expected missing backend error: ${_OUTPUT}${_ERROR}") endif() elseif(NOT _RESULT EQUAL 0) @@ -35,19 +41,21 @@ set(Python_EXECUTABLE python) set(GPU_LANG CUDA) set(CUDA_ARCHS "8.0;8.9;9.0") set(CUDA_KERNEL_ARCHS "8.0;8.9;9.0+PTX") -set(ENV{CUDA_OXIDE_BACKEND} /test/backend.so) -set(_ARGS CUDA_CAPABILITIES 8.0 DEVICE_MANIFEST device/Cargo.toml) +set(CUDA_OXIDE_BACKEND /test/backend.so) +set(_MANIFEST oxide/Cargo.toml) +set(_ARGS CUDA_CAPABILITIES 8.0) if(CASE STREQUAL "cpu") set(GPU_LANG CPU) set(_ARGS) elseif(CASE STREQUAL "host-only") + set(_MANIFEST plain/Cargo.toml) set(_ARGS) elseif(CASE STREQUAL "unsupported-arch") - set(_ARGS CUDA_CAPABILITIES 6.0 DEVICE_MANIFEST device/Cargo.toml) + set(_ARGS CUDA_CAPABILITIES 6.0) elseif(CASE STREQUAL "missing-backend") - unset(ENV{CUDA_OXIDE_BACKEND}) + unset(CUDA_OXIDE_BACKEND) endif() -rust_kernel_component(LIBS TARGETS NAME example MANIFEST_PATH Cargo.toml ${_ARGS}) +rust_kernel_component(LIBS TARGETS NAME example MANIFEST_PATH ${_MANIFEST} ${_ARGS}) if(NOT TARGET example_rust OR NOT TARGET example_cargo_build) message(FATAL_ERROR "Missing shared Cargo/static-library targets") endif() diff --git a/kernels-common/src/config/mod.rs b/kernels-common/src/config/mod.rs index e566dd65..d17fa16f 100644 --- a/kernels-common/src/config/mod.rs +++ b/kernels-common/src/config/mod.rs @@ -356,11 +356,10 @@ pub enum Kernel { depends: Vec, src: Vec, }, - RustCuda { + /// Path of the host crate's `Cargo.toml`, relative to the kernel directory. + /// cuda-oxide device crates are read from its `[package.metadata.cuda-oxide]`. cargo_manifest: String, - device_manifest: Option, - ptx_dir: Option, cuda_capabilities: Option>, depends: Vec, src: Vec, @@ -747,7 +746,7 @@ mod tests { } #[test] - fn v6_rust_cuda_round_trip() { + fn v6_rust_cuda_converts() { let config = r#" [general] name = "rust-cuda" @@ -758,36 +757,19 @@ mod tests { [tvm-ffi] [kernel.gpu_kernel] language = "rust-cuda" - cargo-manifest = "host/Cargo.toml" - device-manifest = "device/Cargo.toml" - ptx-dir = "ptx" + cargo-manifest = "Cargo.toml" cuda-capabilities = ["8.0"] depends = [] - src = ["host/src", "device/src"] + src = ["src"] "#; let build = Build::try_from(toml::from_str::(config).unwrap()).unwrap(); - assert_eq!(build.kernels["gpu_kernel"].language(), Language::Rust); - assert_eq!(build.kernels["gpu_kernel"].backend(), Backend::Cuda); - let serialized = toml::to_string(&v6::Build::from(build)).unwrap(); - let reparsed: v6::Build = toml::from_str(&serialized).unwrap(); - match &reparsed.kernels["gpu_kernel"] { - v6::Kernel::RustCuda { - cargo_manifest, - device_manifest, - ptx_dir, - cuda_capabilities, - .. - } => { - assert_eq!(cargo_manifest, "host/Cargo.toml"); - assert_eq!(device_manifest.as_deref(), Some("device/Cargo.toml")); - assert_eq!(ptx_dir.as_deref(), Some("ptx")); - assert_eq!( - cuda_capabilities.as_deref(), - Some(["8.0".to_string()].as_slice()) - ); - } - _ => panic!("expected Rust CUDA kernel"), - } + let kernel = &build.kernels["gpu_kernel"]; + assert_eq!(kernel.language(), Language::Rust); + assert_eq!(kernel.backend(), Backend::Cuda); + assert!(matches!( + kernel, + Kernel::RustCuda { cuda_capabilities: Some(caps), .. } if caps == &["8.0"] + )); } #[test] diff --git a/kernels-common/src/config/v6.rs b/kernels-common/src/config/v6.rs index b924640d..4c525ed3 100644 --- a/kernels-common/src/config/v6.rs +++ b/kernels-common/src/config/v6.rs @@ -166,12 +166,9 @@ pub enum Kernel { depends: Vec, src: Vec, }, - #[serde(rename_all = "kebab-case")] RustCuda { cargo_manifest: String, - device_manifest: Option, - ptx_dir: Option, cuda_capabilities: Option>, depends: Vec, src: Vec, @@ -394,18 +391,13 @@ impl From for super::Kernel { include, src, }, - Kernel::RustCuda { cargo_manifest, - device_manifest, - ptx_dir, cuda_capabilities, depends, src, } => super::Kernel::RustCuda { cargo_manifest, - device_manifest, - ptx_dir, cuda_capabilities, depends, src, @@ -645,18 +637,13 @@ impl From for Kernel { depends, src, }, - super::Kernel::RustCuda { cargo_manifest, - device_manifest, - ptx_dir, cuda_capabilities, depends, src, } => Kernel::RustCuda { cargo_manifest, - device_manifest, - ptx_dir, cuda_capabilities, depends, src, diff --git a/nix-builder/lib/build.nix b/nix-builder/lib/build.nix index 025c3fbf..a43fd6ca 100644 --- a/nix-builder/lib/build.nix +++ b/nix-builder/lib/build.nix @@ -202,9 +202,6 @@ rec { kernelProvenance ; - rustCudaDevice = lib.any (kernel: kernel.language == "rust-cuda" && kernel ? device-manifest) ( - lib.attrValues kernels - ); cargoLock = if hasRustKernels then src + "/Cargo.lock" else null; rustGitHashes = if hasRustKernels && builtins.pathExists (src + "/rust-git-hashes.json") then diff --git a/nix-builder/lib/extension/tvm-ffi/arch.nix b/nix-builder/lib/extension/tvm-ffi/arch.nix index 6ffccf2b..9b0881b4 100644 --- a/nix-builder/lib/extension/tvm-ffi/arch.nix +++ b/nix-builder/lib/extension/tvm-ffi/arch.nix @@ -62,9 +62,6 @@ # the build has no Rust kernels. cargoLock ? null, - # Compile CUDA device crates with cuda-oxide and its matching rustc. - rustCudaDevice ? false, - # Fixed-output hashes for Git dependencies in Cargo.lock. rustGitHashes ? { }, @@ -139,45 +136,33 @@ let metalSupport = buildConfig.metal or false; rustSupport = cargoLock != null; - rustCuda = import ./rust-cuda.nix { - inherit - pkgs - lib - stdenv - cudaPackages - ; - }; + # Rust CUDA kernels are built with cuda-oxide and its matching rustc. + rustCuda = import ./rust-cuda.nix { inherit pkgs; }; # rpaths are stripped from kernels to make them portable, but that # also means that in a Nix environment the CUDA/ROCm/oneAPI dependencies # cannot be located anymore, so pass them to hooks that load the kernel. - libraryPath = - lib.makeLibraryPath ( - map lib.getLib ( - lib.optionals cudaSupport ( - with cudaPackages; - [ - cuda_cudart - libcublas - libcusolver - libcusparse - ] - ) - ++ lib.optionals rocmSupport [ clr ] - ++ lib.optionals xpuSupport ( - with xpuPackages; - [ - intel-oneapi-compiler-dpcpp-cpp-runtime - intel-oneapi-compiler-shared-runtime - ] - ) + libraryPath = lib.makeLibraryPath ( + map lib.getLib ( + lib.optionals cudaSupport ( + with cudaPackages; + [ + cuda_cudart + libcublas + libcusolver + libcusparse + ] + ) + ++ lib.optionals rocmSupport [ clr ] + ++ lib.optionals xpuSupport ( + with xpuPackages; + [ + intel-oneapi-compiler-dpcpp-cpp-runtime + intel-oneapi-compiler-shared-runtime + ] ) ) - + - lib.optionalString (rustSupport && cudaSupport) - # Import checks run without a GPU driver in the build sandbox. The stub is - # only used by the check hooks, never bundled in the redistributable kernel. - ":${lib.getOutput "stubs" cudaPackages.cuda_cudart}/lib/stubs"; + ); provenanceFlags = import ../provenance-flags.nix { inherit lib kernelProvenance; }; @@ -271,11 +256,11 @@ stdenv.mkDerivation ( ++ lib.optionals rustSupport [ rustPlatform.cargoSetupHook ] - ++ lib.optionals (rustSupport && !rustCudaDevice) [ + ++ lib.optionals (rustSupport && !cudaSupport) [ cargo rustc ] - ++ lib.optionals rustCudaDevice [ rustCuda.toolchain ]; + ++ lib.optionals (rustSupport && cudaSupport) [ rustCuda.toolchain ]; buildInputs = [ python3.pkgs.tvm-ffi @@ -325,10 +310,6 @@ stdenv.mkDerivation ( // lib.optionalAttrs cudaSupport { CUDAToolkit_ROOT = "${lib.getDev cudaPackages.cuda_nvcc}"; } - // lib.optionalAttrs (rustSupport && cudaSupport) rustCuda.env - // lib.optionalAttrs rustCudaDevice { - CUDA_OXIDE_BACKEND = "${rustCuda.backend}/lib/librustc_codegen_cuda.so"; - } // lib.optionalAttrs xpuSupport { MKLROOT = oneapi-torch-dev; SYCL_ROOT = oneapi-torch-dev; @@ -369,6 +350,9 @@ stdenv.mkDerivation ( (lib.cmakeFeature "CMAKE_CUDA_HOST_COMPILER" "${stdenv.cc}/bin/g++") (lib.cmakeFeature "GPU_LANG" "CUDA") ] + ++ lib.optionals (rustSupport && cudaSupport) [ + (lib.cmakeFeature "CUDA_OXIDE_BACKEND" "${rustCuda.backend}/lib/librustc_codegen_cuda.so") + ] ++ lib.optionals rocmSupport [ # Ensure sure that we use HIP from our CLR override and not HIP from # the symlink-joined ROCm toolkit. diff --git a/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix b/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix index cbb20d56..73c91e53 100644 --- a/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix +++ b/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix @@ -1,10 +1,5 @@ # cuda-oxide is a rustc codegen plugin and must use its matching Rust toolchain. -{ - pkgs, - lib, - stdenv, - cudaPackages, -}: +{ pkgs }: let src = pkgs.fetchFromGitHub { owner = "NVIDIA"; @@ -34,27 +29,7 @@ let ]; doCheck = false; }; - cudaHome = pkgs.symlinkJoin { - name = "cuda-home"; - paths = with cudaPackages; [ - (lib.getDev cuda_cudart) - (lib.getLib cuda_cudart) - (lib.getDev cccl) - (lib.getOutput "include" libcurand) - cuda_crt - ]; - }; in { inherit toolchain backend; - env = { - CUDA_HOME = cudaHome; - CUDA_TOOLKIT_PATH = cudaHome; - LIBRARY_PATH = "${lib.getOutput "stubs" cudaPackages.cuda_cudart}/lib/stubs"; - LIBCLANG_PATH = "${lib.getLib pkgs.libclang}/lib"; - BINDGEN_EXTRA_CLANG_ARGS = lib.concatStringsSep " " [ - "-isystem ${lib.getLib pkgs.libclang}/lib/clang/${lib.versions.major pkgs.libclang.version}/include" - "-isystem ${lib.getDev stdenv.cc.libc}/include" - ]; - }; } diff --git a/nix-builder/lib/source-set.nix b/nix-builder/lib/source-set.nix index 36276b75..050606f8 100644 --- a/nix-builder/lib/source-set.nix +++ b/nix-builder/lib/source-set.nix @@ -43,11 +43,7 @@ let else fileset.empty; # Rust kernels also need their Cargo manifest. - kernelSrc = - kernel: - kernel.src - ++ lib.optional (kernel ? cargo-manifest) kernel.cargo-manifest - ++ lib.optional (kernel ? device-manifest) kernel.device-manifest; + kernelSrc = kernel: kernel.src ++ lib.optional (kernel ? cargo-manifest) kernel.cargo-manifest; kernelsSrc = fileset.unions ( lib.flatten (lib.mapAttrsToList (name: kernel: map (nameToPath path) (kernelSrc kernel)) kernels) ); From 5a91c6da5455c162909fe9b9acfd751648c79290 Mon Sep 17 00:00:00 2001 From: David Holtz Date: Tue, 20 Oct 2026 20:33:14 +0000 Subject: [PATCH 3/5] feat: add rust gpu relu example --- examples/kernels/flake.nix | 6 + examples/kernels/relu-rust-cuda/CARD.md | 65 ++++++ examples/kernels/relu-rust-cuda/Cargo.lock | 185 ++++++++++++++++++ examples/kernels/relu-rust-cuda/Cargo.toml | 3 + examples/kernels/relu-rust-cuda/build.toml | 23 +++ examples/kernels/relu-rust-cuda/flake.nix | 17 ++ .../relu-rust-cuda/relu-device/Cargo.toml | 11 ++ .../relu-rust-cuda/relu-device/src/main.rs | 13 ++ .../kernels/relu-rust-cuda/relu-rs/Cargo.toml | 19 ++ .../kernels/relu-rust-cuda/relu-rs/src/lib.rs | 103 ++++++++++ .../relu-rust-cuda/rust-git-hashes.json | 5 + .../kernels/relu-rust-cuda/tests/__init__.py | 0 .../kernels/relu-rust-cuda/tests/test_relu.py | 21 ++ .../tvm-ffi-ext/relu_rust_cuda/__init__.py | 19 ++ 14 files changed, 490 insertions(+) create mode 100644 examples/kernels/relu-rust-cuda/CARD.md create mode 100644 examples/kernels/relu-rust-cuda/Cargo.lock create mode 100644 examples/kernels/relu-rust-cuda/Cargo.toml create mode 100644 examples/kernels/relu-rust-cuda/build.toml create mode 100644 examples/kernels/relu-rust-cuda/flake.nix create mode 100644 examples/kernels/relu-rust-cuda/relu-device/Cargo.toml create mode 100644 examples/kernels/relu-rust-cuda/relu-device/src/main.rs create mode 100644 examples/kernels/relu-rust-cuda/relu-rs/Cargo.toml create mode 100644 examples/kernels/relu-rust-cuda/relu-rs/src/lib.rs create mode 100644 examples/kernels/relu-rust-cuda/rust-git-hashes.json create mode 100644 examples/kernels/relu-rust-cuda/tests/__init__.py create mode 100644 examples/kernels/relu-rust-cuda/tests/test_relu.py create mode 100644 examples/kernels/relu-rust-cuda/tvm-ffi-ext/relu_rust_cuda/__init__.py diff --git a/examples/kernels/flake.nix b/examples/kernels/flake.nix index 1d5b5bed..32d65679 100644 --- a/examples/kernels/flake.nix +++ b/examples/kernels/flake.nix @@ -121,6 +121,12 @@ drv = sys: out: out.packages.${sys}.redistributable.${"tvm-ffi${tvmFfiVersion}-${cudaVersion}-${sys}"}; } + { + name = "relu-rust-cuda-kernel"; + path = ./relu-rust-cuda; + drv = + sys: out: out.packages.${sys}.redistributable.${"tvm-ffi${tvmFfiVersion}-${cudaVersion}-${sys}"}; + } { name = "relu-kernel-cpu"; path = ./relu; diff --git a/examples/kernels/relu-rust-cuda/CARD.md b/examples/kernels/relu-rust-cuda/CARD.md new file mode 100644 index 00000000..2868c79f --- /dev/null +++ b/examples/kernels/relu-rust-cuda/CARD.md @@ -0,0 +1,65 @@ +--- +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 + +# If the org / user isn't a trusted publisher, pass `trust_remote_code=True` to the +# `get_kernel` call. You can find whether this kernel is from a trusted publisher +# by going to the kernel's Hub page and finding the "Trusted publisher" status at +# the top of the page. +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 %} + +## Upstream + +The original source code for this kernel comes from {{ upstream }}. +{% endif %} +{% if source %} + +## Source + +The kernel-builder formatted source for this kernel is available at {{ source }}. +{% endif %} diff --git a/examples/kernels/relu-rust-cuda/Cargo.lock b/examples/kernels/relu-rust-cuda/Cargo.lock new file mode 100644 index 00000000..0496f6e2 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/Cargo.lock @@ -0,0 +1,185 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cuda-device" +version = "0.2.1" +source = "git+https://github.com/NVIDIA/cuda-rust.git?rev=6d47ae49cb256a07948fb499c20c3eb9b2a96268#6d47ae49cb256a07948fb499c20c3eb9b2a96268" +dependencies = [ + "cuda-macros", +] + +[[package]] +name = "cuda-macros" +version = "0.2.1" +source = "git+https://github.com/NVIDIA/cuda-rust.git?rev=6d47ae49cb256a07948fb499c20c3eb9b2a96268#6d47ae49cb256a07948fb499c20c3eb9b2a96268" +dependencies = [ + "proc-macro2", + "quote", + "reserved-oxide-symbols", + "syn 2.0.119", +] + +[[package]] +name = "cudarc" +version = "0.19.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7359bf1de037ddada72729c3acec9b040f3468400c6e9e740b01ba0cd2e89562" +dependencies = [ + "libloading", +] + +[[package]] +name = "libloading" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "relu-device" +version = "0.1.0" +dependencies = [ + "cuda-device", +] + +[[package]] +name = "relu-rs" +version = "0.1.0" +dependencies = [ + "cudarc", + "tvm-ffi", + "tvm-ffi-sys", +] + +[[package]] +name = "reserved-oxide-symbols" +version = "0.2.1" +source = "git+https://github.com/NVIDIA/cuda-rust.git?rev=6d47ae49cb256a07948fb499c20c3eb9b2a96268#6d47ae49cb256a07948fb499c20c3eb9b2a96268" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tvm-ffi" +version = "0.1.14-post1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2573e03b4bc46bfb606b2801c7a94d332b7640acbe5936a0c64935d664ff9875" +dependencies = [ + "paste", + "tvm-ffi-macros", + "tvm-ffi-sys", +] + +[[package]] +name = "tvm-ffi-macros" +version = "0.1.14-post1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c0f660be122ead0def43f986c9ec4aa635bb9e285820adbc449b8230426933f" +dependencies = [ + "proc-macro-error", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "tvm-ffi-sys" +version = "0.1.14-post1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0b29bc4a713c7e86bcb98e1655832058c272eb336f8d62cece8344cb2666ee2" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" diff --git a/examples/kernels/relu-rust-cuda/Cargo.toml b/examples/kernels/relu-rust-cuda/Cargo.toml new file mode 100644 index 00000000..42e2fea8 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/Cargo.toml @@ -0,0 +1,3 @@ +[workspace] +members = ["relu-rs", "relu-device"] +resolver = "2" diff --git a/examples/kernels/relu-rust-cuda/build.toml b/examples/kernels/relu-rust-cuda/build.toml new file mode 100644 index 00000000..7af88b44 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/build.toml @@ -0,0 +1,23 @@ +[general] +name = "relu-rust-cuda" +version = 1 +edition = 6 +license = "Apache-2.0" +backends = ["cuda"] + +[general.hub] +repo-id = "kernels-test/relu-rust-cuda" + +[tvm-ffi] + +[kernel.relu_rust_cuda] +language = "rust-cuda" +cargo-manifest = "relu-rs/Cargo.toml" +cuda-capabilities = ["8.0"] +depends = [] +src = [ + "Cargo.toml", + "relu-rs/src/lib.rs", + "relu-device/Cargo.toml", + "relu-device/src/main.rs", +] diff --git a/examples/kernels/relu-rust-cuda/flake.nix b/examples/kernels/relu-rust-cuda/flake.nix new file mode 100644 index 00000000..e69775eb --- /dev/null +++ b/examples/kernels/relu-rust-cuda/flake.nix @@ -0,0 +1,17 @@ +{ + description = "Flake for a ReLU kernel written in Rust with cuda-oxide"; + + inputs = { + kernel-builder.url = "path:../../.."; + }; + + outputs = + { + self, + kernel-builder, + }: + kernel-builder.lib.genKernelFlakeOutputs { + inherit self; + path = ./.; + }; +} diff --git a/examples/kernels/relu-rust-cuda/relu-device/Cargo.toml b/examples/kernels/relu-rust-cuda/relu-device/Cargo.toml new file mode 100644 index 00000000..649fd8e3 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/relu-device/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "relu-device" +version = "0.1.0" +edition = "2024" +license = "Apache-2.0" +publish = false + +# Kernel-only crate, compiled to PTX by the cuda-oxide codegen backend. Without +# `cuda-host` the kernel macros emit no host glue. +[dependencies] +cuda-device = { git = "https://github.com/NVIDIA/cuda-rust.git", rev = "6d47ae49cb256a07948fb499c20c3eb9b2a96268" } diff --git a/examples/kernels/relu-rust-cuda/relu-device/src/main.rs b/examples/kernels/relu-rust-cuda/relu-device/src/main.rs new file mode 100644 index 00000000..c3c57fea --- /dev/null +++ b/examples/kernels/relu-rust-cuda/relu-device/src/main.rs @@ -0,0 +1,13 @@ +use cuda_device::{DisjointSlice, kernel, thread}; + +#[kernel] +pub fn relu(x: &[f32], mut out: DisjointSlice) { + let idx = thread::index_1d(); + let i = idx.get(); + if let Some(slot) = out.get_mut(idx) { + let v = x[i]; + *slot = if v > 0.0 { v } else { 0.0 }; + } +} + +fn main() {} diff --git a/examples/kernels/relu-rust-cuda/relu-rs/Cargo.toml b/examples/kernels/relu-rust-cuda/relu-rs/Cargo.toml new file mode 100644 index 00000000..22365719 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/relu-rs/Cargo.toml @@ -0,0 +1,19 @@ +[package] +name = "relu-rs" +version = "0.1.0" +edition = "2021" +license = "Apache-2.0" +publish = false + +# Kernel-builder compiles these with cuda-oxide before this crate and passes +# the PTX directory as `KERNEL_BUILDER_PTX_DIR`. +[[package.metadata.cuda-oxide.device-crates]] +manifest-path = "../relu-device/Cargo.toml" + +[lib] +name = "relu_rust_cuda" + +[dependencies] +cudarc = { version = "0.19.9", default-features = false, features = ["std", "driver", "dynamic-loading", "cuda-12060"] } +tvm-ffi = "=0.1.14-post1" +tvm-ffi-sys = "=0.1.14-post1" diff --git a/examples/kernels/relu-rust-cuda/relu-rs/src/lib.rs b/examples/kernels/relu-rust-cuda/relu-rs/src/lib.rs new file mode 100644 index 00000000..e574c397 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/relu-rs/src/lib.rs @@ -0,0 +1,103 @@ +use std::collections::HashMap; +use std::ffi::{c_void, CString}; +use std::sync::{Arc, Mutex, OnceLock}; + +use cudarc::driver::{result, sys, CudaContext}; +use tvm_ffi::{Error, Result, Tensor, RUNTIME_ERROR, VALUE_ERROR}; +use tvm_ffi_sys::dlpack::{DLDataTypeCode, DLDeviceType}; +use tvm_ffi_sys::TVMFFIEnvGetStream; + +// PTX of the `relu-device` crate, NUL-terminated for `cuModuleLoadData`. +const PTX: &str = concat!( + include_str!(concat!(env!("KERNEL_BUILDER_PTX_DIR"), "/relu_device.ptx")), + "\0" +); + +struct Relu { + ctx: Arc, + function: sys::CUfunction, +} + +unsafe impl Send for Relu {} + +fn cuda_error(e: result::DriverError) -> Error { + Error::new(RUNTIME_ERROR, &format!("{e:?}"), "") +} + +fn value_error(message: &str) -> Error { + Error::new(VALUE_ERROR, message, "") +} + +// Loads the module once per device into the primary context Torch also uses. +fn with_relu(device: i32, f: impl FnOnce(&Relu) -> Result) -> Result { + static RELU: OnceLock>> = OnceLock::new(); + let mut loaded = RELU.get_or_init(Default::default).lock().unwrap(); + if !loaded.contains_key(&device) { + let ctx = CudaContext::new(device as usize).map_err(cuda_error)?; + ctx.bind_to_thread().map_err(cuda_error)?; + let function = unsafe { + let module = result::module::load_data(PTX.as_ptr().cast()).map_err(cuda_error)?; + result::module::get_function(module, CString::new("relu").unwrap()) + .map_err(cuda_error)? + }; + loaded.insert(device, Relu { ctx, function }); + } + f(&loaded[&device]) +} + +fn relu_rust_cuda(x: Tensor, out: Tensor) -> Result<()> { + let f32_type = |t: &Tensor| { + let dtype = t.dtype(); + dtype.code == DLDataTypeCode::kDLFloat as u8 && dtype.bits == 32 && dtype.lanes == 1 + }; + if !f32_type(&x) || !f32_type(&out) { + return Err(value_error("input and output must be float32")); + } + if !x.is_contiguous() || !out.is_contiguous() { + return Err(value_error("input and output must be contiguous")); + } + if x.numel() != out.numel() { + return Err(value_error(&format!( + "input and output must have the same number of elements, got {} and {}", + x.numel(), + out.numel() + ))); + } + let device = x.device(); + if device.device_type != DLDeviceType::kDLCUDA || out.device() != device { + return Err(value_error( + "input and output must be on the same CUDA device", + )); + } + if x.numel() == 0 { + return Ok(()); + } + + with_relu(device.device_id, |relu| { + relu.ctx.bind_to_thread().map_err(cuda_error)?; + let stream = unsafe { TVMFFIEnvGetStream(DLDeviceType::kDLCUDA as i32, device.device_id) }; + // Slices are passed to cuda-oxide kernels as (pointer, length) pairs. + let (mut x_ptr, mut out_ptr) = (x.data_ptr() as u64, out.data_ptr() as u64); + let mut len = x.numel() as u64; + let mut params = [ + (&mut x_ptr as *mut u64).cast::(), + (&mut len as *mut u64).cast(), + (&mut out_ptr as *mut u64).cast(), + (&mut len as *mut u64).cast(), + ]; + let blocks = len.div_ceil(256) as u32; + unsafe { + result::launch_kernel( + relu.function, + (blocks, 1, 1), + (256, 1, 1), + 0, + stream.cast(), + &mut params, + ) + } + .map_err(cuda_error) + }) +} + +tvm_ffi::tvm_ffi_dll_export_typed_func!(relu_rust_cuda, relu_rust_cuda); diff --git a/examples/kernels/relu-rust-cuda/rust-git-hashes.json b/examples/kernels/relu-rust-cuda/rust-git-hashes.json new file mode 100644 index 00000000..7e8a2a46 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/rust-git-hashes.json @@ -0,0 +1,5 @@ +{ + "cuda-device-0.2.1": "sha256-KxIPPzDBKeHyknrpRg1ekNliEcc44yBWUtSmrGnApOo=", + "cuda-macros-0.2.1": "sha256-KxIPPzDBKeHyknrpRg1ekNliEcc44yBWUtSmrGnApOo=", + "reserved-oxide-symbols-0.2.1": "sha256-KxIPPzDBKeHyknrpRg1ekNliEcc44yBWUtSmrGnApOo=" +} diff --git a/examples/kernels/relu-rust-cuda/tests/__init__.py b/examples/kernels/relu-rust-cuda/tests/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/examples/kernels/relu-rust-cuda/tests/test_relu.py b/examples/kernels/relu-rust-cuda/tests/test_relu.py new file mode 100644 index 00000000..7b642fac --- /dev/null +++ b/examples/kernels/relu-rust-cuda/tests/test_relu.py @@ -0,0 +1,21 @@ +import kernels +import pytest +import torch +import torch.nn.functional as F + +relu_rust_cuda = kernels.get_kernel("kernels-test/relu-rust-cuda", version=1) + + +@pytest.mark.kernels_ci +def test_relu(): + x = torch.randn(1024, 1024, dtype=torch.float32, device="cuda") + torch.testing.assert_close( + F.relu(x), relu_rust_cuda.relu(x, torch.empty_like(x)) + ) + + +@pytest.mark.kernels_ci +def test_rejects_mismatched_output(): + x = torch.randn(16, dtype=torch.float32, device="cuda") + with pytest.raises(Exception, match="same number of elements"): + relu_rust_cuda.relu(x, torch.empty(32, dtype=torch.float32, device="cuda")) diff --git a/examples/kernels/relu-rust-cuda/tvm-ffi-ext/relu_rust_cuda/__init__.py b/examples/kernels/relu-rust-cuda/tvm-ffi-ext/relu_rust_cuda/__init__.py new file mode 100644 index 00000000..c665c751 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/tvm-ffi-ext/relu_rust_cuda/__init__.py @@ -0,0 +1,19 @@ +import tvm_ffi + +from ._ops import ops + + +def relu(x, out): + x_t = tvm_ffi.from_dlpack(x) + out_t = tvm_ffi.from_dlpack(out) + + device = x_t.device + if device.type == "cuda": + ops.relu_rust_cuda(x_t, out_t) + else: + raise NotImplementedError(f"Unsupported device type: {device.type}") + + return out + + +__all__ = ["relu"] From 9fedf1756f3c00ba431efcd5ed2d6b38e96d22c7 Mon Sep 17 00:00:00 2001 From: David Holtz Date: Tue, 20 Oct 2026 21:30:59 +0000 Subject: [PATCH 4/5] fix: package cuda-oxide and build rust cuda with the kernel stdenv --- docs/source/builder/writing-kernels.md | 21 ++++++++++ .../src/pyproject/templates/rust.cmake | 7 +--- nix-builder/lib/cache.nix | 2 + nix-builder/lib/extension/tvm-ffi/arch.nix | 14 ++----- nix-builder/lib/source-set.nix | 1 - nix-builder/overlay.nix | 3 ++ .../cuda-oxide/default.nix} | 39 ++++++++++++++----- 7 files changed, 61 insertions(+), 26 deletions(-) rename nix-builder/{lib/extension/tvm-ffi/rust-cuda.nix => pkgs/cuda-oxide/default.nix} (54%) diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index 9c57b294..c819bdb2 100644 --- a/docs/source/builder/writing-kernels.md +++ b/docs/source/builder/writing-kernels.md @@ -377,6 +377,27 @@ in Git so Nix can include them in the build. Rerun the command whenever Git dependencies in `Cargo.lock` change. Registry dependencies use the checksums in `Cargo.lock` and do not require this file. +#### rust-cuda (experimental, and subject to change) + +Rust CUDA kernels use [cuda-oxide](https://github.com/NVIDIA/cuda-rust) and +take the same options as `rust-cpu`, plus: + +- `cuda-capabilities` (optional): same as for `cpp-cuda`. PTX is generated for the lowest supported capability, so set this when kernels use newer instructions. + +`cargo-manifest` points to the host crate. It lists its device crates, which must be in the same Cargo workspace, in its metadata: + +```toml +[[package.metadata.cuda-oxide.device-crates]] +manifest-path = "../relu-device/Cargo.toml" +``` + +The device crates are built first and the host crate finds their PTX in `KERNEL_BUILDER_PTX_DIR`. + +Use the cuda-rust revision pinned in +[`cuda-oxide`](https://github.com/huggingface/kernels/blob/main/nix-builder/pkgs/cuda-oxide/default.nix). +See [`relu-rust-cuda`](https://github.com/huggingface/kernels/tree/main/examples/kernels/relu-rust-cuda) +for an example. + ## Torch bindings ### Defining bindings diff --git a/kernel-builder/src/pyproject/templates/rust.cmake b/kernel-builder/src/pyproject/templates/rust.cmake index 1b791f06..5feb65ca 100644 --- a/kernel-builder/src/pyproject/templates/rust.cmake +++ b/kernel-builder/src/pyproject/templates/rust.cmake @@ -65,14 +65,13 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) accumulate_gpu_archs(_ALL_GPU_ARCHS "${ALL_GPU_ARCHS}" "${_KERNEL_ARCHS}") set(ALL_GPU_ARCHS ${_ALL_GPU_ARCHS} PARENT_SCOPE) - endif() - set(_HOST_ENV) - if(GPU_LANG STREQUAL "CUDA") _cuda_oxide_device_manifests(_DEVICE_MANIFESTS ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH}) endif() + set(_HOST_ENV) + if(_DEVICE_MANIFESTS) # Build cuda-oxide device code before the host crate embeds its PTX. if(NOT CUDA_OXIDE_BACKEND) @@ -126,8 +125,6 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) add_custom_target(${KERNEL_NAME}_cargo_build ALL COMMAND ${CMAKE_COMMAND} -E env "PATH=${_PYTHON_BIN_DIR}:$ENV{PATH}" - "KERNEL_BUILDER_GPU_LANG=${GPU_LANG}" - "KERNEL_BUILDER_CUDA_ARCHS=${_KERNEL_ARCHS}" ${_HOST_ENV} ${CARGO_EXECUTABLE} rustc --release --locked --lib --crate-type staticlib --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH} diff --git a/nix-builder/lib/cache.nix b/nix-builder/lib/cache.nix index 49c5f56f..22624e2e 100644 --- a/nix-builder/lib/cache.nix +++ b/nix-builder/lib/cache.nix @@ -34,6 +34,8 @@ ++ allOutputs python3.pkgs.tvm-ffi ++ allOutputs ruff ++ lib.optionals (isLinux && cudaSupport) (allOutputs manylinux_2_28.cudaBackendStdenv) + ++ lib.optionals (isLinux && cudaSupport) (allOutputs cuda-oxide.toolchain) + ++ lib.optionals (isLinux && cudaSupport) (allOutputs cuda-oxide.backend) ++ lib.optionals (isLinux && !config.cudaSupport) (allOutputs manylinux_2_28.stdenv) # Only works on recent CUDAs. ++ lib.optionals (!python3.pkgs.nvidia-cutlass-dsl.meta.broken) ( diff --git a/nix-builder/lib/extension/tvm-ffi/arch.nix b/nix-builder/lib/extension/tvm-ffi/arch.nix index 9b0881b4..cba89576 100644 --- a/nix-builder/lib/extension/tvm-ffi/arch.nix +++ b/nix-builder/lib/extension/tvm-ffi/arch.nix @@ -13,6 +13,7 @@ cargo, cmake, cmakeNvccThreadsHook, + cuda-oxide, cuda_nvcc, generate-symbols-hook, get-kernel-check, @@ -136,8 +137,6 @@ let metalSupport = buildConfig.metal or false; rustSupport = cargoLock != null; - # Rust CUDA kernels are built with cuda-oxide and its matching rustc. - rustCuda = import ./rust-cuda.nix { inherit pkgs; }; # rpaths are stripped from kernels to make them portable, but that # also means that in a Nix environment the CUDA/ROCm/oneAPI dependencies @@ -260,7 +259,8 @@ stdenv.mkDerivation ( cargo rustc ] - ++ lib.optionals (rustSupport && cudaSupport) [ rustCuda.toolchain ]; + # Rust CUDA kernels are built with cuda-oxide and its matching rustc. + ++ lib.optionals (rustSupport && cudaSupport) [ cuda-oxide.toolchain ]; buildInputs = [ python3.pkgs.tvm-ffi @@ -340,18 +340,12 @@ stdenv.mkDerivation ( # rpaths anyway. (lib.cmakeBool "CMAKE_SKIP_RPATH" true) ] - # Rust toolchains can propagate a newer compiler onto PATH. Link with the - # selected stdenv so redistributable kernels retain their glibc baseline. - ++ lib.optionals rustSupport [ - (lib.cmakeFeature "CMAKE_C_COMPILER" "${stdenv.cc}/bin/cc") - (lib.cmakeFeature "CMAKE_CXX_COMPILER" "${stdenv.cc}/bin/c++") - ] ++ lib.optionals cudaSupport [ (lib.cmakeFeature "CMAKE_CUDA_HOST_COMPILER" "${stdenv.cc}/bin/g++") (lib.cmakeFeature "GPU_LANG" "CUDA") ] ++ lib.optionals (rustSupport && cudaSupport) [ - (lib.cmakeFeature "CUDA_OXIDE_BACKEND" "${rustCuda.backend}/lib/librustc_codegen_cuda.so") + (lib.cmakeFeature "CUDA_OXIDE_BACKEND" "${cuda-oxide.backend}/lib/librustc_codegen_cuda.so") ] ++ lib.optionals rocmSupport [ # Ensure sure that we use HIP from our CLR override and not HIP from diff --git a/nix-builder/lib/source-set.nix b/nix-builder/lib/source-set.nix index 050606f8..a1d75909 100644 --- a/nix-builder/lib/source-set.nix +++ b/nix-builder/lib/source-set.nix @@ -55,7 +55,6 @@ fileset.toSource { kernelsSrc lockSet cargoLockSet - (fileset.maybeMissing (path + "/rust-toolchain.toml")) rustGitHashesSet srcSet pySrcSet diff --git a/nix-builder/overlay.nix b/nix-builder/overlay.nix index 99f8a58f..0873f4e5 100644 --- a/nix-builder/overlay.nix +++ b/nix-builder/overlay.nix @@ -39,6 +39,9 @@ final: prev: }; }; + # cuda-oxide toolchain and codegen backend for Rust CUDA kernels. + cuda-oxide = final.callPackage ./pkgs/cuda-oxide { }; + lock-kernel-deps = final.callPackage ./pkgs/lock-kernel-deps { }; # Make the source for a package from our cargo workspace. diff --git a/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix b/nix-builder/pkgs/cuda-oxide/default.nix similarity index 54% rename from nix-builder/lib/extension/tvm-ffi/rust-cuda.nix rename to nix-builder/pkgs/cuda-oxide/default.nix index 73c91e53..7b526cce 100644 --- a/nix-builder/lib/extension/tvm-ffi/rust-cuda.nix +++ b/nix-builder/pkgs/cuda-oxide/default.nix @@ -1,18 +1,40 @@ # cuda-oxide is a rustc codegen plugin and must use its matching Rust toolchain. -{ pkgs }: +{ + fetchFromGitHub, + libffi, + libxml2, + makeRustPlatform, + rust-bin, + zlib, + zstd, +}: + let - src = pkgs.fetchFromGitHub { + src = fetchFromGitHub { owner = "NVIDIA"; repo = "cuda-rust"; rev = "6d47ae49cb256a07948fb499c20c3eb9b2a96268"; hash = "sha256-g9qg2zHLybO8kPLoOJqnYbWjRYtjGV3QVT+X4f8+1fg="; }; - toolchain = pkgs.rust-bin.fromRustupToolchainFile "${src}/cuda-oxide/rust-toolchain.toml"; - platform = pkgs.makeRustPlatform { + + # rust-overlay propagates the compiler of its own package set. Drop it so + # kernels link with their (manylinux) stdenv, as with the rust-cpu toolchain. + toolchain = + (rust-bin.fromRustupToolchainFile "${src}/cuda-oxide/rust-toolchain.toml").overrideAttrs + { + propagatedBuildInputs = [ ]; + depsHostHostPropagated = [ ]; + }; + + rustPlatform = makeRustPlatform { cargo = toolchain; rustc = toolchain; }; - backend = platform.buildRustPackage { +in +{ + inherit toolchain; + + backend = rustPlatform.buildRustPackage { pname = "rustc-codegen-cuda"; version = "0.2.1"; inherit src; @@ -21,15 +43,12 @@ let lockFile = "${src}/cuda-oxide/crates/rustc-codegen-cuda/Cargo.lock"; outputHashes."pliron-0.18.0" = "sha256-HQ/xNfQcIf9pQRrgxCYGFdVfdCMaE4iwj/G9mgAJOWw="; }; - buildInputs = with pkgs; [ + buildInputs = [ libffi libxml2 - zstd zlib + zstd ]; doCheck = false; }; -in -{ - inherit toolchain backend; } From 1cfb75aaa9a574693e52624ba8b73c3d0df03d0f Mon Sep 17 00:00:00 2001 From: David Holtz Date: Tue, 20 Oct 2026 21:53:36 +0000 Subject: [PATCH 5/5] fix: remove low value test --- kernels-common/src/config/mod.rs | 33 -------------------------------- 1 file changed, 33 deletions(-) diff --git a/kernels-common/src/config/mod.rs b/kernels-common/src/config/mod.rs index d17fa16f..5631ab1b 100644 --- a/kernels-common/src/config/mod.rs +++ b/kernels-common/src/config/mod.rs @@ -745,33 +745,6 @@ mod tests { assert_eq!(build.kernels["cpu_kernel"].language(), Language::Rust); } - #[test] - fn v6_rust_cuda_converts() { - let config = r#" - [general] - name = "rust-cuda" - version = 1 - edition = 6 - license = "Apache-2.0" - backends = ["cuda"] - [tvm-ffi] - [kernel.gpu_kernel] - language = "rust-cuda" - cargo-manifest = "Cargo.toml" - cuda-capabilities = ["8.0"] - depends = [] - src = ["src"] - "#; - let build = Build::try_from(toml::from_str::(config).unwrap()).unwrap(); - let kernel = &build.kernels["gpu_kernel"]; - assert_eq!(kernel.language(), Language::Rust); - assert_eq!(kernel.backend(), Backend::Cuda); - assert!(matches!( - kernel, - Kernel::RustCuda { cuda_capabilities: Some(caps), .. } if caps == &["8.0"] - )); - } - #[test] fn v6_rust_kernel_rejects_invalid_config() { let cases = [ @@ -781,12 +754,6 @@ mod tests { "", "require a `[tvm-ffi]` framework", ), - ( - "[tvm-ffi]", - "rust-cuda", - r#"cuda-flags = ["-O3"]"#, - "unknown field `cuda-flags`", - ), ( "[tvm-ffi]", "rust-cpu",