diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index 48c9bddf..c819bdb2 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). @@ -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/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"] 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..7ccfe5a7 100644 --- a/kernel-builder/src/pyproject/kernel.rs +++ b/kernel-builder/src/pyproject/kernel.rs @@ -40,6 +40,22 @@ fn render_kernel_component( Kernel::RustCpu { cargo_manifest, .. } => { render_kernel_component_rust(env, kernel_name, cargo_manifest, write)? } + Kernel::RustCuda { + cargo_manifest, + cuda_capabilities, + .. + } => { + env.get_template("kernel-component/rust-cuda.cmake")? + .render_captured_to( + context! { + name => kernel_name, + manifest_path => cargo_manifest, + 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 +254,48 @@ 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, capabilities) in [ + ( + Kernel::RustCpu { + cargo_manifest: "host/Cargo.toml".into(), + depends: vec![], + src: vec![], + }, + "CPU", + None, + ), + ( + Kernel::RustCuda { + cargo_manifest: "host/Cargo.toml".into(), + cuda_capabilities: Some(vec!["8.0".into(), "9.0".into()]), + depends: vec![], + src: vec![], + }, + "CUDA", + Some("CUDA_CAPABILITIES 8.0 9.0"), + ), + ] { + 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("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 new file mode 100644 index 00000000..83ff7ba3 --- /dev/null +++ b/kernel-builder/src/pyproject/templates/kernel-component/rust-cuda.cmake @@ -0,0 +1,7 @@ +if(GPU_LANG STREQUAL "CUDA") + rust_kernel_component(RUST_KERNEL_LIBS RUST_KERNEL_TARGETS + NAME {{ name }} + MANIFEST_PATH "{{ manifest_path }}" + {% 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..5feb65ca 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" "" ${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") @@ -10,6 +52,68 @@ 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) + + _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) + message(FATAL_ERROR "rust_kernel_component: cuda-oxide device crates require CUDA_OXIDE_BACKEND") + endif() + + set(_DEVICE_TARGET_DIR ${CMAKE_BINARY_DIR}/cargo/${KERNEL_NAME}-device) + set(_PTX_DIR ${_DEVICE_TARGET_DIR}/ptx) + 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() + + 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} + ${_DEVICE_COMMANDS} + WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} + COMMENT "Building Rust CUDA device kernel ${KERNEL_NAME}" + VERBATIM + ) + list(APPEND _HOST_ENV "KERNEL_BUILDER_PTX_DIR=${_PTX_DIR}") + endif() + string(REPLACE "-" "_" _LIB_NAME ${KERNEL_NAME}) set(_CARGO_TARGET_DIR ${CMAKE_BINARY_DIR}/cargo/${KERNEL_NAME}) @@ -21,6 +125,7 @@ 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}" + ${_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} @@ -29,6 +134,9 @@ function(rust_kernel_component LIBS_VAR TARGETS_VAR) 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}) diff --git a/kernel-builder/tests/rust-components.cmake b/kernel-builder/tests/rust-components.cmake new file mode 100644 index 00000000..6b435009 --- /dev/null +++ b/kernel-builder/tests/rust-components.cmake @@ -0,0 +1,68 @@ +# 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}" + 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 "require 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(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) +elseif(CASE STREQUAL "missing-backend") + unset(CUDA_OXIDE_BACKEND) +endif() +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() +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..5631ab1b 100644 --- a/kernels-common/src/config/mod.rs +++ b/kernels-common/src/config/mod.rs @@ -356,6 +356,14 @@ 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, + cuda_capabilities: Option>, + depends: Vec, + src: Vec, + }, CppCuda { cuda_capabilities: Option>, cuda_flags: Option>, @@ -396,7 +404,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 +415,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 +429,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 +443,7 @@ impl Kernel { | Kernel::CppMetal { .. } | Kernel::CppRocm { .. } | Kernel::CppXpu { .. } => Language::Cpp, - Kernel::RustCpu { .. } => Language::Rust, + Kernel::RustCpu { .. } | Kernel::RustCuda { .. } => Language::Rust, } } @@ -443,6 +451,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 +463,7 @@ impl Kernel { match self { Kernel::CppCpu { src, .. } | Kernel::RustCpu { src, .. } + | Kernel::RustCuda { src, .. } | Kernel::CppCuda { src, .. } | Kernel::CppMetal { src, .. } | Kernel::CppRocm { src, .. } @@ -738,6 +748,12 @@ mod tests { #[test] fn v6_rust_kernel_rejects_invalid_config() { let cases = [ + ( + "[torch]\nsrc = []", + "rust-cuda", + "", + "require a `[tvm-ffi]` framework", + ), ( "[tvm-ffi]", "rust-cpu", diff --git a/kernels-common/src/config/v6.rs b/kernels-common/src/config/v6.rs index c4f621f4..4c525ed3 100644 --- a/kernels-common/src/config/v6.rs +++ b/kernels-common/src/config/v6.rs @@ -167,6 +167,13 @@ pub enum Kernel { src: Vec, }, #[serde(rename_all = "kebab-case")] + RustCuda { + cargo_manifest: String, + cuda_capabilities: Option>, + depends: Vec, + src: Vec, + }, + #[serde(rename_all = "kebab-case")] CppCuda { cuda_capabilities: Option>, cuda_flags: Option>, @@ -224,10 +231,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 +391,17 @@ impl From for super::Kernel { include, src, }, + Kernel::RustCuda { + cargo_manifest, + cuda_capabilities, + depends, + src, + } => super::Kernel::RustCuda { + cargo_manifest, + cuda_capabilities, + depends, + src, + }, Kernel::RustCpu { cargo_manifest, depends, @@ -617,6 +637,17 @@ impl From for Kernel { depends, src, }, + super::Kernel::RustCuda { + cargo_manifest, + cuda_capabilities, + depends, + src, + } => Kernel::RustCuda { + cargo_manifest, + cuda_capabilities, + depends, + src, + }, super::Kernel::CppCuda { cuda_capabilities, cuda_flags, 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 f3cec3c7..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, @@ -253,9 +254,13 @@ stdenv.mkDerivation ( ] ++ lib.optionals rustSupport [ rustPlatform.cargoSetupHook + ] + ++ lib.optionals (rustSupport && !cudaSupport) [ cargo rustc - ]; + ] + # Rust CUDA kernels are built with cuda-oxide and its matching rustc. + ++ lib.optionals (rustSupport && cudaSupport) [ cuda-oxide.toolchain ]; buildInputs = [ python3.pkgs.tvm-ffi @@ -339,6 +344,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" "${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 # the symlink-joined ROCm toolkit. 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/pkgs/cuda-oxide/default.nix b/nix-builder/pkgs/cuda-oxide/default.nix new file mode 100644 index 00000000..7b526cce --- /dev/null +++ b/nix-builder/pkgs/cuda-oxide/default.nix @@ -0,0 +1,54 @@ +# cuda-oxide is a rustc codegen plugin and must use its matching Rust toolchain. +{ + fetchFromGitHub, + libffi, + libxml2, + makeRustPlatform, + rust-bin, + zlib, + zstd, +}: + +let + src = fetchFromGitHub { + owner = "NVIDIA"; + repo = "cuda-rust"; + rev = "6d47ae49cb256a07948fb499c20c3eb9b2a96268"; + hash = "sha256-g9qg2zHLybO8kPLoOJqnYbWjRYtjGV3QVT+X4f8+1fg="; + }; + + # 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; + }; +in +{ + inherit toolchain; + + backend = rustPlatform.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 = [ + libffi + libxml2 + zlib + zstd + ]; + doCheck = false; + }; +}