diff --git a/docs/source/builder/writing-kernels.md b/docs/source/builder/writing-kernels.md index 48c9bddf..c38d02f8 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,31 @@ 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 are built with +[cuda-oxide](https://github.com/NVIDIA/cuda-rust) and take the same options as +`rust-cpu`, plus: + +- `cuda-capabilities` (optional): same as for `cuda`. Like with `nvcc`, the + kernels are compiled once per capability, to SASS, so nothing is JIT-compiled + at load time. Each pass sets `cfg(cuda_arch = "XX")` for its capability and + every lower one, so `#[cfg(cuda_arch = "90")]` works like + `__CUDA_ARCH__ >= 900`. + +Rust CUDA kernels require CUDA 13.0 or later, so they are only built for +CUDA 13.0+ build variants (a lower `general.cuda.minver` is raised to 13.0). The CUDA +bindings are generated with bindgen during the build, so building outside of +Nix requires a CUDA 13 toolkit (found via `CUDA_TOOLKIT_PATH` or `CUDA_HOME`) +and libclang. + +An extension can have only one `rust-cuda` component. Use the cuda-rust +revision pinned in +[`cuda-oxide`](https://github.com/huggingface/kernels/blob/main/nix-builder/pkgs/cuda-oxide/default.nix) +and 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..ca84296d 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}-${cuda13Version}-${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..02bf5ced --- /dev/null +++ b/examples/kernels/relu-rust-cuda/Cargo.lock @@ -0,0 +1,860 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bindgen" +version = "0.69.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools", + "lazy_static", + "lazycell", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex", + "syn 2.0.119", + "which", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cuda-artifact-finalizer" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "libnvvm-sys", + "nvjitlink-sys", + "serde", + "sha2", + "thiserror", +] + +[[package]] +name = "cuda-bindings" +version = "0.4.0" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "bindgen", + "libloading", + "prettyplease", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "cuda-core" +version = "0.4.0" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "anyhow", + "cuda-bindings", + "cuda-core-derive", + "half", + "oxide-artifacts", +] + +[[package]] +name = "cuda-core-derive" +version = "0.4.0" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "cuda-device" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "cuda-macros", +] + +[[package]] +name = "cuda-host" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "cuda-artifact-finalizer", + "cuda-core", + "cuda-macros", + "half", + "libc", + "oxide-artifacts", + "ptx-parse", + "sha2", + "thiserror", +] + +[[package]] +name = "cuda-macros" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "oxide-tile-export", + "proc-macro2", + "quote", + "reserved-oxide-symbols", + "syn 2.0.119", +] + +[[package]] +name = "cuda-target-spec" +version = "0.1.0" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "home" +version = "0.5.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589533453244b0995c858700322199b2becb13b627df2851f64a2775d024abcf" +dependencies = [ + "windows-sys 0.59.0", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "itertools" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba291022dbbd398a455acf126c1e341954079855bc60dfdda641363bd6922569" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "kernels-cuda" +version = "0.1.0" +source = "git+https://github.com/huggingface/kernels.git?rev=ae983e7ce660d4ed3a1142d6b9a540b7576be47d#ae983e7ce660d4ed3a1142d6b9a540b7576be47d" +dependencies = [ + "cuda-core", + "half", + "tvm-ffi", + "tvm-ffi-sys", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lazycell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830d08ce1d1d941e6b30645f1a0eb5643013d835ce3779a5fc208261dbe10f55" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libnvvm-sys" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "cuda-target-spec", + "libloading", + "thiserror", +] + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nvjitlink-sys" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "libloading", + "thiserror", +] + +[[package]] +name = "object" +version = "0.36.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62948e14d923ea95ea2c7c86c71013138b66525b86bdc08d2dcc262bdb497b87" +dependencies = [ + "crc32fast", + "hashbrown 0.15.5", + "indexmap", + "memchr", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "oxide-artifacts" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74d9a941c0c43d2dceaf25f5c9ca4c9f9cceb28dfa5e4e3cfd14e476f003e7c9" +dependencies = [ + "object", +] + +[[package]] +name = "oxide-tile-export" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" +dependencies = [ + "serde", + "serde_json", + "thiserror", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[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 = "ptx-parse" +version = "0.1.0" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "relu-rust-cuda" +version = "0.1.0" +dependencies = [ + "cuda-core", + "cuda-device", + "cuda-host", + "kernels-cuda", + "tvm-ffi", +] + +[[package]] +name = "reserved-oxide-symbols" +version = "0.2.1" +source = "git+https://github.com/drbh/cuda-oxide.git?rev=d9d4e379e9a80d1ce7c681d88a086aacec95ba23#d9d4e379e9a80d1ce7c681d88a086aacec95ba23" + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.59.0", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[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 = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[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 = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[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 = "which" +version = "4.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87ba24419a2078cd2b0f2ede2691b6c66d8e47836da3b6db8265ebad47afbfc7" +dependencies = [ + "either", + "home", + "once_cell", + "rustix", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/examples/kernels/relu-rust-cuda/Cargo.toml b/examples/kernels/relu-rust-cuda/Cargo.toml new file mode 100644 index 00000000..71f145ed --- /dev/null +++ b/examples/kernels/relu-rust-cuda/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "relu-rust-cuda" +version = "0.1.0" +edition = "2024" +license = "Apache-2.0" +publish = false + +[lib] +name = "relu_rust_cuda" + +[workspace] + +# The kernel and its host code live in this crate. Kernel-builder compiles it +# with the cuda-oxide codegen backend and links the kernels as SASS. +[dependencies] +cuda-core = { git = "https://github.com/drbh/cuda-oxide.git", rev = "d9d4e379e9a80d1ce7c681d88a086aacec95ba23" } +cuda-device = { git = "https://github.com/drbh/cuda-oxide.git", rev = "d9d4e379e9a80d1ce7c681d88a086aacec95ba23" } +cuda-host = { git = "https://github.com/drbh/cuda-oxide.git", rev = "d9d4e379e9a80d1ce7c681d88a086aacec95ba23" } +tvm-ffi = "=0.1.14-post1" +kernels-cuda = { git = "https://github.com/huggingface/kernels.git", rev = "ae983e7ce660d4ed3a1142d6b9a540b7576be47d" } diff --git a/examples/kernels/relu-rust-cuda/build.toml b/examples/kernels/relu-rust-cuda/build.toml new file mode 100644 index 00000000..1017f06b --- /dev/null +++ b/examples/kernels/relu-rust-cuda/build.toml @@ -0,0 +1,18 @@ +[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 = "Cargo.toml" +cuda-capabilities = ["8.0", "9.0", "10.0", "12.0"] +depends = [] +src = ["Cargo.toml", "Cargo.lock", "src/lib.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/rust-git-hashes.json b/examples/kernels/relu-rust-cuda/rust-git-hashes.json new file mode 100644 index 00000000..d76d6986 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/rust-git-hashes.json @@ -0,0 +1,16 @@ +{ + "cuda-artifact-finalizer-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-bindings-0.4.0": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-core-0.4.0": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-core-derive-0.4.0": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-device-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-host-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-macros-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "cuda-target-spec-0.1.0": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "kernels-cuda-0.1.0": "sha256-DQA+7fZEc7jCz8XMm4pldbHgT3bncTWHqgroiKE8XBQ=", + "libnvvm-sys-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "nvjitlink-sys-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "oxide-tile-export-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "ptx-parse-0.1.0": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=", + "reserved-oxide-symbols-0.2.1": "sha256-cz53C3hB3dxVrVLgX+KtZ4WGT+jjoazNsBSedODCFrg=" +} diff --git a/examples/kernels/relu-rust-cuda/src/lib.rs b/examples/kernels/relu-rust-cuda/src/lib.rs new file mode 100644 index 00000000..a79b2ca8 --- /dev/null +++ b/examples/kernels/relu-rust-cuda/src/lib.rs @@ -0,0 +1,44 @@ +use cuda_core::simt::LaunchConfig; +use cuda_device::cuda_module; +use kernels_cuda::cuda_error; +use tvm_ffi::{Error, Result, Tensor, VALUE_ERROR}; + +#[cuda_module] +mod kernels { + 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 relu_rust_cuda(x: Tensor, out: Tensor) -> Result<()> { + if x.numel() != out.numel() { + return Err(Error::new( + VALUE_ERROR, + &format!( + "input and output must have the same number of elements, got {} and {}", + x.numel(), + out.numel() + ), + "", + )); + } + if x.numel() == 0 { + return Ok(()); + } + + let gpu = kernels_cuda::load(x.device(), kernels::from_module)?; + let x = gpu.view::(&x)?; + let mut out = gpu.view::(&out)?; + let config = LaunchConfig::for_num_elems(x.len() as u32); + unsafe { gpu.module.relu(&gpu.stream, config, &x, &mut out) }.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/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-fatbin.cpp.in b/kernel-builder/src/pyproject/templates/rust-fatbin.cpp.in new file mode 100644 index 00000000..bd004c93 --- /dev/null +++ b/kernel-builder/src/pyproject/templates/rust-fatbin.cpp.in @@ -0,0 +1,16 @@ +// Links the fatbin of the Rust kernel component @NAME@ into the extension. +// +// The image goes in nvcc's `.nv_fatbin` section, so cuobjdump finds the SASS. +// Unlike nvcc's fatbins it is not registered with the CUDA runtime: the crate +// loads it itself with `cuModuleLoadData`. +__asm__( + ".section .nv_fatbin, \"a\"\n" + ".balign 16\n" + ".globl KERNEL_BUILDER_CUDA_FATBIN\n" + ".hidden KERNEL_BUILDER_CUDA_FATBIN\n" + "KERNEL_BUILDER_CUDA_FATBIN:\n" + ".incbin \"@FATBIN@\"\n" + ".globl KERNEL_BUILDER_CUDA_FATBIN_END\n" + ".hidden KERNEL_BUILDER_CUDA_FATBIN_END\n" + "KERNEL_BUILDER_CUDA_FATBIN_END:\n" + ".previous\n"); diff --git a/kernel-builder/src/pyproject/templates/rust.cmake b/kernel-builder/src/pyproject/templates/rust.cmake index 727fff42..e93ece67 100644 --- a/kernel-builder/src/pyproject/templates/rust.cmake +++ b/kernel-builder/src/pyproject/templates/rust.cmake @@ -1,5 +1,9 @@ +# Functions run with the caller's CMAKE_CURRENT_LIST_DIR, so remember where the +# templates beside this file are. +set(_RUST_CMAKE_DIR ${CMAKE_CURRENT_LIST_DIR}) + 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,33 +14,198 @@ 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) + + # The crate is built with the cuda-oxide codegen backend, which compiles + # host code as usual and writes the device code as PTX. + if(NOT CUDA_OXIDE_BACKEND) + message(FATAL_ERROR "rust_kernel_component: Rust CUDA kernels require CUDA_OXIDE_BACKEND") + endif() + + # The fatbin is linked in under fixed symbol names. + get_property(_FATBIN_OWNER GLOBAL PROPERTY RUST_CUDA_FATBIN_OWNER) + if(_FATBIN_OWNER) + message(FATAL_ERROR "rust_kernel_component: ${KERNEL_NAME} and ${_FATBIN_OWNER} " + "are both Rust CUDA components; only one is supported per extension") + endif() + set_property(GLOBAL PROPERTY RUST_CUDA_FATBIN_OWNER ${KERNEL_NAME}) + + get_filename_component(_CUDA_BIN_DIR "${CMAKE_CUDA_COMPILER}" DIRECTORY) + find_program(CUDA_PTXAS_EXECUTABLE ptxas HINTS ${_CUDA_BIN_DIR} REQUIRED) + find_program(CUDA_FATBINARY_EXECUTABLE fatbinary HINTS ${_CUDA_BIN_DIR} REQUIRED) + # Without libdevice, cuda-oxide silently emits NVVM IR instead of PTX + # for kernels that call `__nv_*` functions (e.g. `__nv_expf`). + find_file(CUDA_LIBDEVICE libdevice.10.bc + HINTS ${_CUDA_BIN_DIR}/../nvvm/libdevice NO_DEFAULT_PATH REQUIRED) + if(NOT CMAKE_OBJCOPY) + message(FATAL_ERROR "rust_kernel_component: Rust CUDA kernels require objcopy") + endif() + + set(_SMS) + set(_PTX_SMS) + foreach(_ARCH IN LISTS _KERNEL_ARCHS) + _rust_cuda_sm(_SM ${_ARCH}) + list(APPEND _SMS ${_SM}) + if(_ARCH MATCHES "\\+PTX$") + list(APPEND _PTX_SMS ${_SM}) + endif() + endforeach() + # Flags match what `cargo oxide build` passes to the codegen backend. + set(_RUSTFLAGS "-Zcodegen-backend=${CUDA_OXIDE_BACKEND} -Copt-level=3 -Cdebug-assertions=off -Zmir-enable-passes=-JumpThreading -Csymbol-mangling-version=v0 --check-cfg=cfg(cuda_arch,values(any()))") + endif() + string(REPLACE "-" "_" _LIB_NAME ${KERNEL_NAME}) set(_CARGO_TARGET_DIR ${CMAKE_BINARY_DIR}/cargo/${KERNEL_NAME}) set(_STATICLIB ${_CARGO_TARGET_DIR}/release/${CMAKE_STATIC_LIBRARY_PREFIX}${_LIB_NAME}${CMAKE_STATIC_LIBRARY_SUFFIX}) + set(_LINKED_STATICLIB ${_STATICLIB}) + set(_BYPRODUCTS ${_STATICLIB}) # tvm-ffi-sys's build script shells out to `tvm-ffi-config`, a console script # the apache-tvm-ffi wheel installs beside the interpreter. get_filename_component(_PYTHON_BIN_DIR ${Python_EXECUTABLE} DIRECTORY) + set(_CARGO_COMMAND ${CMAKE_COMMAND} -E env "PATH=${_PYTHON_BIN_DIR}:$ENV{PATH}") + set(_CARGO_ARGS rustc --release --locked --lib --crate-type staticlib + --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH}) + + if(GPU_LANG STREQUAL "CUDA") + # Like nvcc's `-gencode`, compile the device code once per capability, + # with `cuda_arch` set for it and every lower capability, so kernels can + # branch on it like on `__CUDA_ARCH__`. The first pass also builds the + # host code we link. + set(_COMMANDS) + set(_PTXS) + foreach(_SM IN LISTS _SMS) + if(NOT _COMMANDS) + set(_PASS_DIR ${_CARGO_TARGET_DIR}) + else() + set(_PASS_DIR ${_CARGO_TARGET_DIR}/sm_${_SM}) + endif() + _rust_cuda_cfgs(_CFGS ${_SM}) + list(APPEND _COMMANDS COMMAND ${_CARGO_COMMAND} + "CUDA_OXIDE_TARGET=sm_${_SM}" + "CUDA_OXIDE_PTX_DIR=${_PASS_DIR}/ptx" + "CUDA_OXIDE_LIBDEVICE=${CUDA_LIBDEVICE}" + "RUSTFLAGS=${_RUSTFLAGS} ${_CFGS}" + ${CARGO_EXECUTABLE} ${_CARGO_ARGS} --target-dir ${_PASS_DIR}) + list(APPEND _PTXS ${_PASS_DIR}/ptx/${_LIB_NAME}.ptx) + endforeach() + list(APPEND _BYPRODUCTS ${_PTXS}) + # The backend also embeds the PTX in the crate's `.oxart` sections. The + # extension loads the fatbin instead, so drop the PTX from what we link. + set(_LINKED_STATICLIB ${_CARGO_TARGET_DIR}/${CMAKE_STATIC_LIBRARY_PREFIX}${_LIB_NAME}_sass${CMAKE_STATIC_LIBRARY_SUFFIX}) + list(APPEND _BYPRODUCTS ${_LINKED_STATICLIB}) + # The launchers keep the host copies of the kernels alive, so their calls + # into libdevice (`__nv_*`, linked into the device code only) stay + # unresolved. The host copies never run: weaken those references. + # Keeping the date lets a no-op cargo build skip the relink. + set(_STRIP_PTX COMMAND ${CMAKE_OBJCOPY} --preserve-dates --remove-section=.oxart + --wildcard --weaken-symbol=__nv_* + ${_STATICLIB} ${_LINKED_STATICLIB}) + else() + set(_COMMANDS COMMAND ${_CARGO_COMMAND} + ${CARGO_EXECUTABLE} ${_CARGO_ARGS} --target-dir ${_CARGO_TARGET_DIR}) + endif() add_custom_target(${KERNEL_NAME}_cargo_build ALL - COMMAND ${CMAKE_COMMAND} -E env "PATH=${_PYTHON_BIN_DIR}:$ENV{PATH}" - ${CARGO_EXECUTABLE} rustc --release --locked --lib --crate-type staticlib - --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/${KERNEL_MANIFEST_PATH} - --target-dir ${_CARGO_TARGET_DIR} - BYPRODUCTS ${_STATICLIB} + ${_COMMANDS} + ${_STRIP_PTX} + BYPRODUCTS ${_BYPRODUCTS} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Building Rust kernel ${KERNEL_NAME} with cargo" VERBATIM ) add_library(${KERNEL_NAME}_rust STATIC IMPORTED GLOBAL) - set_target_properties(${KERNEL_NAME}_rust PROPERTIES IMPORTED_LOCATION ${_STATICLIB}) + set_target_properties(${KERNEL_NAME}_rust PROPERTIES IMPORTED_LOCATION ${_LINKED_STATICLIB}) + + if(GPU_LANG STREQUAL "CUDA") + _rust_cuda_fatbin(${KERNEL_NAME} "${_SMS}" "${_PTXS}" "${_PTX_SMS}") + endif() set(${LIBS_VAR} ${${LIBS_VAR}} ${KERNEL_NAME}_rust PARENT_SCOPE) set(${TARGETS_VAR} ${${TARGETS_VAR}} ${KERNEL_NAME}_cargo_build PARENT_SCOPE) endfunction() +# The capability as in `sm_XX`. +function(_rust_cuda_sm OUT ARCH) + string(REPLACE "+PTX" "" _SM "${ARCH}") + string(REPLACE "." "" _SM "${_SM}") + set(${OUT} ${_SM} PARENT_SCOPE) +endfunction() + +# `cuda_arch` cfgs for one pass: every capability in CUDA_ARCHS up to SM, so a +# cfg means "this capability or newer", plus SM itself when it is arch-specific. +function(_rust_cuda_cfgs OUT SM) + string(REGEX REPLACE "[a-z]+$" "" _NUM ${SM}) + set(_KNOWN) + foreach(_ARCH IN LISTS CUDA_ARCHS) + _rust_cuda_sm(_KNOWN_SM ${_ARCH}) + string(REGEX REPLACE "[a-z]+$" "" _KNOWN_SM ${_KNOWN_SM}) + list(APPEND _KNOWN ${_KNOWN_SM}) + endforeach() + list(REMOVE_DUPLICATES _KNOWN) + set(_CFGS) + foreach(_KNOWN_SM IN LISTS _KNOWN) + if(_KNOWN_SM LESS_EQUAL _NUM) + list(APPEND _CFGS "--cfg=cuda_arch=\"${_KNOWN_SM}\"") + endif() + endforeach() + if(NOT SM STREQUAL _NUM) + list(APPEND _CFGS "--cfg=cuda_arch=\"${SM}\"") + endif() + list(JOIN _CFGS " " _CFGS) + set(${OUT} "${_CFGS}" PARENT_SCOPE) +endfunction() + +# Compiles each pass's PTX to SASS, so nothing is JIT-compiled on the user's +# machine. `target_link_rust_kernels` links the fatbin between +# `KERNEL_BUILDER_CUDA_FATBIN` and `KERNEL_BUILDER_CUDA_FATBIN_END`. +function(_rust_cuda_fatbin NAME SMS PTXS PTX_SMS) + list(GET PTXS 0 _FIRST_PTX) + get_filename_component(_DIR ${_FIRST_PTX} DIRECTORY) + set(_CUBINS) + set(_IMAGES) + foreach(_SM _PTX IN ZIP_LISTS SMS PTXS) + set(_CUBIN ${_DIR}/${NAME}.sm_${_SM}.cubin) + add_custom_command(OUTPUT ${_CUBIN} + COMMAND ${CUDA_PTXAS_EXECUTABLE} -arch=sm_${_SM} ${_PTX} -o ${_CUBIN} + DEPENDS ${_PTX} + COMMENT "Compiling Rust kernel ${NAME} for sm_${_SM}" + VERBATIM) + list(APPEND _CUBINS ${_CUBIN}) + list(APPEND _IMAGES "--image3=kind=elf,sm=${_SM},file=${_CUBIN}") + if(_SM IN_LIST PTX_SMS) + list(APPEND _IMAGES "--image3=kind=ptx,sm=${_SM},file=${_PTX}") + endif() + endforeach() + + set(_FATBIN ${_DIR}/${NAME}.fatbin) + add_custom_command(OUTPUT ${_FATBIN} + COMMAND ${CUDA_FATBINARY_EXECUTABLE} --create=${_FATBIN} ${_IMAGES} + DEPENDS ${_CUBINS} ${PTXS} + COMMENT "Creating fatbin for Rust kernel ${NAME}" + VERBATIM) + + set(_SOURCE ${CMAKE_CURRENT_BINARY_DIR}/${NAME}_fatbin.cpp) + set(FATBIN ${_FATBIN}) + configure_file(${_RUST_CMAKE_DIR}/rust-fatbin.cpp.in ${_SOURCE} @ONLY) + set_source_files_properties(${_SOURCE} PROPERTIES OBJECT_DEPENDS ${_FATBIN}) + set_property(GLOBAL PROPERTY RUST_CUDA_FATBIN_SOURCE ${_SOURCE}) +endfunction() + # `add_library(SHARED)` errors on an empty source list, and a Rust-only # extension has none: the crate exports the tvm-ffi entry points itself. function(rust_extension_sources SRC_VAR) @@ -83,4 +252,16 @@ function(target_link_rust_kernels TARGET) Threads::Threads ${CMAKE_DL_LIBS}) _restrict_rust_exports(${TARGET}) + if(UNIX AND NOT APPLE) + # The codegen backend's embedded PTX objects carry no `.note.GNU-stack`, + # which would otherwise make the linker mark the stack executable. + target_link_options(${TARGET} PRIVATE "LINKER:-z,noexecstack") + get_property(_FATBIN_SOURCE GLOBAL PROPERTY RUST_CUDA_FATBIN_SOURCE) + if(_FATBIN_SOURCE) + target_sources(${TARGET} PRIVATE ${_FATBIN_SOURCE}) + # A crate that still calls the generated `load` references the + # embedded PTX we removed. Fail the link instead of the import. + target_link_options(${TARGET} PRIVATE "LINKER:--no-undefined") + endif() + endif() endfunction() diff --git a/kernel-builder/src/pyproject/tvm_ffi/mod.rs b/kernel-builder/src/pyproject/tvm_ffi/mod.rs index 32cd0301..dab8cbc9 100644 --- a/kernel-builder/src/pyproject/tvm_ffi/mod.rs +++ b/kernel-builder/src/pyproject/tvm_ffi/mod.rs @@ -17,6 +17,7 @@ use crate::pyproject::FileSet; static BUILD_VARIANTS_UTILS: &str = include_str!("../templates/tvm_ffi/build-variants.cmake"); static CMAKE_KERNEL: &str = include_str!("../templates/kernel.cmake"); static CMAKE_RUST: &str = include_str!("../templates/rust.cmake"); +static CMAKE_RUST_FATBIN: &str = include_str!("../templates/rust-fatbin.cpp.in"); static CMAKE_UTILS: &str = include_str!("../templates/utils.cmake"); static HIPIFY: &str = include_str!("../templates/tvm_ffi/hipify.py"); static OPS_PY_IN: &str = include_str!("../templates/tvm_ffi/_ops.py.in"); @@ -27,6 +28,7 @@ fn write_cmake_helpers(file_set: &mut FileSet) { write_cmake_file(file_set, "utils.cmake", CMAKE_UTILS.as_bytes()); write_cmake_file(file_set, "kernel.cmake", CMAKE_KERNEL.as_bytes()); write_cmake_file(file_set, "rust.cmake", CMAKE_RUST.as_bytes()); + write_cmake_file(file_set, "rust-fatbin.cpp.in", CMAKE_RUST_FATBIN.as_bytes()); write_cmake_file( file_set, "build-variants.cmake", diff --git a/kernel-builder/tests/rust-components.cmake b/kernel-builder/tests/rust-components.cmake new file mode 100644 index 00000000..9b64b72e --- /dev/null +++ b/kernel-builder/tests/rust-components.cmake @@ -0,0 +1,76 @@ +# 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") + file(WRITE "${_TEST_DIR}/crate/Cargo.toml" + "[package]\nname = \"example\"\nversion = \"0.0.0\"\nedition = \"2021\"\n[lib]\npath = \"lib.rs\"\n[workspace]\n") + file(TOUCH "${_TEST_DIR}/crate/lib.rs") + foreach(_CASE cpu cuda unsupported-arch missing-backend two-components) + 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(_CASE STREQUAL "two-components") + if(_RESULT EQUAL 0 OR NOT _ERROR MATCHES "only one is supported") + message(FATAL_ERROR "Expected two components 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(CUDA_PTXAS_EXECUTABLE /test/ptxas) +set(CUDA_FATBINARY_EXECUTABLE /test/fatbinary) +set(CMAKE_OBJCOPY /test/objcopy) +set(_ARGS CUDA_CAPABILITIES 8.0) +if(CASE STREQUAL "cpu") + set(GPU_LANG CPU) + 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 crate/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 ALL_GPU_ARCHS STREQUAL "8.0") + message(FATAL_ERROR "Incorrect capabilities: ${ALL_GPU_ARCHS}") + endif() + get_property(_SOURCE GLOBAL PROPERTY RUST_CUDA_FATBIN_SOURCE) + if(NOT _SOURCE MATCHES "example_fatbin.cpp$") + message(FATAL_ERROR "Missing fatbin source: ${_SOURCE}") + endif() + file(READ ${_SOURCE} _CONTENTS) + if(NOT _CONTENTS MATCHES "\\.incbin [^\n]*/example\\.fatbin") + message(FATAL_ERROR "Fatbin source does not include the fatbin:\n${_CONTENTS}") + endif() +elseif(CASE STREQUAL "two-components") + rust_kernel_component(LIBS TARGETS NAME other MANIFEST_PATH crate/Cargo.toml ${_ARGS}) +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/kernels-cuda/Cargo.toml b/kernels-cuda/Cargo.toml new file mode 100644 index 00000000..539b18d3 --- /dev/null +++ b/kernels-cuda/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "kernels-cuda" +version = "0.1.0" +edition = "2024" +license = "Apache-2.0" +description = "Runtime support for kernel-builder's rust-cuda kernels" +publish = false + +[dependencies] +cuda-core = { git = "https://github.com/drbh/cuda-oxide.git", rev = "d9d4e379e9a80d1ce7c681d88a086aacec95ba23" } +half = "2" +tvm-ffi = "=0.1.14-post1" +tvm-ffi-sys = "=0.1.14-post1" + +# Kernel crates depend on cuda-oxide, so keep it out of the root workspace. +[workspace] diff --git a/kernels-cuda/src/lib.rs b/kernels-cuda/src/lib.rs new file mode 100644 index 00000000..25adabb9 --- /dev/null +++ b/kernels-cuda/src/lib.rs @@ -0,0 +1,188 @@ +//! Runtime support for kernel-builder's `rust-cuda` kernels. +//! +//! kernel-builder compiles a kernel crate's PTX for every CUDA capability in +//! `build.toml` and links the fatbin into the extension. [`load`] loads that +//! fatbin into the device's primary context, which Torch also uses, binds it +//! to a `#[cuda_module]` and borrows the caller's current stream. +//! [`Gpu::view`] wraps Torch tensors as `DeviceBuffer`s without taking +//! ownership. +//! +//! ```ignore +//! fn relu(x: Tensor, out: Tensor) -> tvm_ffi::Result<()> { +//! let gpu = kernels_cuda::load(x.device(), kernels::from_module)?; +//! let (x, mut out) = (gpu.view::(&x)?, gpu.view::(&out)?); +//! let config = LaunchConfig::for_num_elems(x.len() as u32); +//! unsafe { gpu.module.relu(&gpu.stream, config, &x, &mut out) } +//! .map_err(kernels_cuda::cuda_error) +//! } +//! ``` + +use std::any::{Any, TypeId}; +use std::collections::BTreeMap; +use std::collections::btree_map::Entry; +use std::mem::ManuallyDrop; +use std::ops::{Deref, DerefMut}; +use std::sync::{Arc, Mutex}; + +use cuda_core::{CudaContext, CudaModule, CudaStream, DeviceBuffer, DriverError}; +use tvm_ffi::{Error, RUNTIME_ERROR, Result, Tensor, VALUE_ERROR}; +use tvm_ffi_sys::TVMFFIEnvGetStream; +use tvm_ffi_sys::dlpack::{DLDataTypeCode, DLDevice, DLDeviceType}; + +// kernel-builder links the fatbin between these symbols. +unsafe extern "C" { + static KERNEL_BUILDER_CUDA_FATBIN: u8; + static KERNEL_BUILDER_CUDA_FATBIN_END: u8; +} + +fn fatbin() -> &'static [u8] { + let start = &raw const KERNEL_BUILDER_CUDA_FATBIN; + let end = &raw const KERNEL_BUILDER_CUDA_FATBIN_END; + unsafe { std::slice::from_raw_parts(start, end.offset_from(start) as usize) } +} + +/// Converts a CUDA error, such as a failed launch, to a tvm-ffi error. +pub fn cuda_error(e: impl std::fmt::Debug) -> Error { + Error::new(RUNTIME_ERROR, &format!("{e:?}"), "") +} + +fn value_error(message: &str) -> Error { + Error::new(VALUE_ERROR, message, "") +} + +/// A loaded module and the caller's current stream on one device. +/// +/// The stream is borrowed for the current call, so don't keep a `Gpu` after +/// returning to the caller. +pub struct Gpu { + pub module: Arc, + pub stream: Arc, + ctx: Arc, + device_id: i32, +} + +type Loaded = (Arc, Arc); + +/// Loads the kernels for `device` once and binds them with `from_module`, +/// the function `#[cuda_module]` generates. +pub fn load( + device: DLDevice, + from_module: fn(Arc) -> std::result::Result, +) -> Result> { + if device.device_type != DLDeviceType::kDLCUDA { + return Err(value_error("expected a CUDA device")); + } + static LOADED: Mutex> = Mutex::new(BTreeMap::new()); + let (ctx, module) = match LOADED + .lock() + .unwrap() + .entry((device.device_id, TypeId::of::())) + { + Entry::Occupied(entry) => entry.get().clone(), + Entry::Vacant(entry) => { + let ctx = CudaContext::new(device.device_id as usize).map_err(cuda_error)?; + let module = ctx + .load_module_from_image(fatbin()) + .and_then(from_module) + .map_err(cuda_error)?; + entry.insert((ctx, Arc::new(module))).clone() + } + }; + let module = module.downcast::().expect("modules are keyed by type"); + + ctx.bind_to_thread().map_err(cuda_error)?; + // Torch's current stream, which Torch keeps owning. + let stream = unsafe { + let raw = TVMFFIEnvGetStream(DLDeviceType::kDLCUDA as i32, device.device_id); + CudaStream::borrow_raw(raw, &ctx) + }; + Ok(Gpu { + module, + stream, + ctx, + device_id: device.device_id, + }) +} + +impl Gpu { + /// Views a contiguous `T` tensor on this device as a `DeviceBuffer`. + pub fn view(&self, tensor: &Tensor) -> Result> { + let device = tensor.device(); + if device.device_type != DLDeviceType::kDLCUDA || device.device_id != self.device_id { + return Err(value_error(&format!( + "tensors must be on cuda:{}", + self.device_id + ))); + } + let dtype = tensor.dtype(); + if dtype.code != T::CODE as u8 || dtype.bits != T::BITS || dtype.lanes != 1 { + return Err(value_error(&format!( + "expected a {} tensor", + std::any::type_name::() + ))); + } + if !tensor.is_contiguous() { + return Err(value_error("tensors must be contiguous")); + } + let ptr = tensor.data_ptr() as u64; + // SAFETY: the tensor owns `numel` elements of `T` at `ptr` on this + // device. `View` never frees them. + let buffer = unsafe { DeviceBuffer::from_raw_parts(ptr, tensor.numel(), self.ctx.clone()) }; + Ok(View(ManuallyDrop::new(buffer))) + } +} + +/// A tensor's memory as a `DeviceBuffer`. Dropping it leaves the memory to +/// the tensor. +pub struct View(ManuallyDrop>); + +impl Deref for View { + type Target = DeviceBuffer; + + fn deref(&self) -> &DeviceBuffer { + &self.0 + } +} + +impl DerefMut for View { + fn deref_mut(&mut self) -> &mut DeviceBuffer { + &mut self.0 + } +} + +impl Drop for View { + fn drop(&mut self) { + let buffer = unsafe { ManuallyDrop::take(&mut self.0) }; + let _ = buffer.into_raw_parts(); + } +} + +/// An element type with a DLPack equivalent. +pub trait Element { + const CODE: DLDataTypeCode; + const BITS: u8; +} + +macro_rules! element { + ($($ty:ty => $code:ident, $bits:literal;)*) => { + $(impl Element for $ty { + const CODE: DLDataTypeCode = DLDataTypeCode::$code; + const BITS: u8 = $bits; + })* + }; +} + +element! { + i8 => kDLInt, 8; + i16 => kDLInt, 16; + i32 => kDLInt, 32; + i64 => kDLInt, 64; + u8 => kDLUInt, 8; + u16 => kDLUInt, 16; + u32 => kDLUInt, 32; + u64 => kDLUInt, 64; + half::f16 => kDLFloat, 16; + f32 => kDLFloat, 32; + f64 => kDLFloat, 64; + half::bf16 => kDLBfloat, 16; +} diff --git a/nix-builder/lib/build.nix b/nix-builder/lib/build.nix index a43fd6ca..3d8a512e 100644 --- a/nix-builder/lib/build.nix +++ b/nix-builder/lib/build.nix @@ -48,7 +48,13 @@ rec { # Step 1: build sets within the given bounds. buildSetsWithinBounds = let - minCuda = kernelConfig.toml.general.cuda.minver or "11.8"; + # Rust CUDA kernels generate their CUDA bindings with bindgen, which + # requires CUDA 13.0 or later headers. + minCuda = + let + minver = kernelConfig.toml.general.cuda.minver or "11.8"; + in + if kernelConfig.usesRustCuda && lib.versionOlder minver "13.0" then "13.0" else minver; maxCuda = kernelConfig.toml.general.cuda.maxver or "99.9"; minTorch = kernelConfig.toml.torch.minver or "2.0"; maxTorch = kernelConfig.toml.torch.maxver or "99.9"; diff --git a/nix-builder/lib/cache.nix b/nix-builder/lib/cache.nix index 49c5f56f..5afbd7da 100644 --- a/nix-builder/lib/cache.nix +++ b/nix-builder/lib/cache.nix @@ -20,6 +20,8 @@ inherit (buildSet) overrideTorch; isLinux = stdenv.hostPlatform.isLinux; cudaSupport = config.cudaSupport; + # Rust CUDA kernels are only built for CUDA 13.0 and later. + rustCudaSupport = cudaSupport && lib.versionAtLeast buildSet.buildConfig.cudaVersion "13.0"; xpuSupport = config.xpuSupport or false; in ( @@ -34,6 +36,8 @@ ++ allOutputs python3.pkgs.tvm-ffi ++ allOutputs ruff ++ lib.optionals (isLinux && cudaSupport) (allOutputs manylinux_2_28.cudaBackendStdenv) + ++ lib.optionals (isLinux && rustCudaSupport) (allOutputs cuda-oxide.toolchain) + ++ lib.optionals (isLinux && rustCudaSupport) (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..b16a0f81 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, @@ -137,6 +138,16 @@ let rustSupport = cargoLock != null; + # cuda-bindings runs bindgen against a single CUDA include directory that + # must provide both `cuda.h` and `curand.h`. + rustCudaToolkit = pkgs.symlinkJoin { + name = "rust-cuda-toolkit"; + paths = with cudaPackages; [ + (lib.getInclude cuda_cudart) + (lib.getInclude libcurand) + ]; + }; + # 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. @@ -253,8 +264,16 @@ 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 + # libclang for the cuda-bindings build script. + rustPlatform.bindgenHook ]; buildInputs = [ @@ -305,6 +324,9 @@ stdenv.mkDerivation ( // lib.optionalAttrs cudaSupport { CUDAToolkit_ROOT = "${lib.getDev cudaPackages.cuda_nvcc}"; } + // lib.optionalAttrs (rustSupport && cudaSupport) { + CUDA_TOOLKIT_PATH = "${rustCudaToolkit}"; + } // lib.optionalAttrs xpuSupport { MKLROOT = oneapi-torch-dev; SYCL_ROOT = oneapi-torch-dev; @@ -339,6 +361,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/lib/kernel-config.nix b/nix-builder/lib/kernel-config.nix index 60c7ca58..c3c571d1 100644 --- a/nix-builder/lib/kernel-config.nix +++ b/nix-builder/lib/kernel-config.nix @@ -77,5 +77,10 @@ in in lib.foldl (backends: kernel: backends // { ${kernelBackend kernel} = true; }) init kernels; + # Does the kernel have Rust CUDA (cuda-oxide) components. + usesRustCuda = lib.any (kernel: kernelLanguage kernel == "rust" && kernelBackend kernel == "cuda") ( + lib.attrValues (toml.kernel or { }) + ); + name = toml.general.name; } 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..6ba36ef7 --- /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 + # NVIDIA/cuda-rust main with `CudaStream::borrow_raw`, which kernels need to + # launch on the Torch stream. Move back to NVIDIA/cuda-rust once + # https://github.com/NVIDIA/cuda-rust/pull/1601 is merged. + src = fetchFromGitHub { + owner = "drbh"; + repo = "cuda-oxide"; + rev = "d9d4e379e9a80d1ce7c681d88a086aacec95ba23"; + hash = "sha256-/rfi6TODuZp/YSoAy/bpse3nYJSokpmMwg3bHTtCNBM="; + }; + + # 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"; + buildInputs = [ + libffi + libxml2 + zlib + zstd + ]; + doCheck = false; + }; +}