Rust CUDA Setup: Compile Your First GPU Kernel
In this article
This guide walks you through setting up Rust for CUDA development and compiling a simple GPU kernel. By the end, you'll have a working Rust project that launches a kernel on an NVIDIA GPU using the rust-cuda ecosystem (specifically the rustacuda crate). This approach lets you write GPU code in Rust without C/C++, while still using the CUDA runtime and driver underneath.
What You'll Need
- An NVIDIA GPU with CUDA Compute Capability 3.5 or higher (check with
nvidia-smi). - NVIDIA CUDA Toolkit (version 10.0 or newer) installed, including the
nvcccompiler and CUDA driver. Download from NVIDIA's website. - Rust toolchain (stable or nightly; nightly is required for some features, but stable works for this guide). Install via
rustup. - A C++ compiler (e.g., GCC on Linux, MSVC on Windows) because CUDA's build tools rely on it.
- Basic familiarity with Rust syntax and command line.
Step-by-Step
- Verify CUDA installation – Run
nvcc --versionin a terminal. If it fails, reinstall the CUDA Toolkit and ensure thebindirectory is in your PATH. Also runnvidia-smito confirm your GPU is detected. - Install Rust – If you haven't already, install Rust via
rustup. Use the default stable toolchain. Verify withrustc --version. - Create a new Rust project – Run
cargo new rust_cuda_exampleand enter the directory:cd rust_cuda_example. - Add dependencies – Edit
Cargo.tomland add the following under[dependencies]:
These crates provide safe wrappers for CUDA. For a more low-level approach, you could userustacuda = "0.2" rustacuda_derive = "0.2"cuda-sys, but we'll stick withrustacuda. - Write the kernel – Create a file named
kernel.cuin the project root. This is CUDA C code that will be compiled to PTX (the GPU's instruction set). For this example, write a simple kernel that adds 1.0 to each element of a float array:
Theextern "C" __global__ void add_one(float *data, int n) { int idx = blockIdx.x * blockDim.x + threadIdx.x; if (idx < n) { data[idx] += 1.0f; } }extern "C"is important so the symbol name is not mangled. - Compile the kernel to PTX – Use
nvccto compile the kernel to PTX (a portable intermediate representation). Run:
This generatesnvcc --ptx -o kernel.ptx kernel.cukernel.ptxin the same folder. If you get errors, ensure CUDA is correctly installed. - Write the Rust host code – Replace the contents of
src/main.rswith the following:
Note: Theuse rustacuda::prelude::*; use rustacuda::error::CudaError; use std::error::Error; fn main() -> Result<(), Box> { // Initialize the CUDA driver rustacuda::init(CudaFlags::empty())?; // Get the first available device let device = Device::get_device(0)?; let _ctx = Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device)?; // Load the PTX module let module = Module::load_from_file("kernel.ptx")?; // Create a stream (optional, but good practice) let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?; // Prepare data: a vector of 10 floats let mut host_data = vec![0.0f32; 10]; let mut device_data = DeviceBuffer::from_slice(&host_data)?; // Launch the kernel: 1 block, 10 threads unsafe { let result = module.get_function("add_one")?.launch( &stream, (1, 1, 1), // grid dimensions (10, 1, 1), // block dimensions (&mut device_data, host_data.len() as i32), ); result?; } // Synchronize and copy data back stream.synchronize()?; device_data.copy_to(&mut host_data)?; // Print results println!("Result: {:?}", host_data); Ok(()) } unsafeblock is required because launching a kernel is unsafe in the wrapper. - Run the project – In the terminal, run
cargo run. If everything is set up correctly, you should seeResult: [1.0, 1.0, ...](all ones).
Common Mistakes
- Forgetting to compile the kernel to PTX – The Rust program expects a
kernel.ptxfile. If you skip step 6, you'll get a file-not-found error. - Using the wrong CUDA version – The
rustacudacrate requires CUDA 10.0+. If you have an older version, you'll see linking errors. Check withnvcc --version. - Not setting the correct grid/block dimensions – If your grid/block size is too small, some elements won't be processed. For example, if you have 10 elements and use 1 block of 5 threads, only 5 elements are updated.
- Ignoring the
extern "C"in the kernel – Without it, the function name gets mangled, and the Rust code won't find it. - Using stable Rust with features that require nightly – Some crates or features might need nightly. For this guide, stable works, but if you hit issues, try
rustup default nightly.
Tips
- Use
cargo build --releasefor optimized performance in production. - Check your GPU's compute capability and compile PTX for that architecture to get better performance:
nvcc --ptx -arch=sm_70 kernel.cu(replace with your capability). - Error handling: The
?operator is used, but you might want to add more context withmap_errfor debugging. - For larger projects, consider using
rustacuda_coredirectly for more control. - Always call
stream.synchronize()before reading results to ensure the kernel has finished.
Troubleshooting
- Error:
cudaErrorInsufficientDriver– Your CUDA driver is too old. Update the NVIDIA driver and reinstall the CUDA Toolkit. - Error:
module not found– Make surekernel.ptxis in the same directory as your executable (or adjust the path inModule::load_from_file). - Linker errors about
cudart– This usually means the CUDA library path is not set. On Linux, addexport LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATHto your shell profile. - Kernel launches but results are unchanged – Check your grid/block dimensions. If you have 10 elements and use a block size of 10, that's fine. If you use 1 block of 5, only 5 elements get updated.
- Compilation errors with
nvcc– Ensure you have a C++ compiler installed (gcc, clang, or MSVC). On Windows, you may need to runnvccfrom a Visual Studio developer command prompt.
Frequently Asked Questions
Can I use Rust without writing any CUDA C code?
Yes, there are crates like cudarc that allow you to write kernels in Rust using inline PTX, but it's more complex. The approach above uses CUDA C for the kernel, which is the most common and stable method.
Is this the same as using CUDA in C++?
Under the hood, it uses the same CUDA runtime and driver. The main difference is that the host code is in Rust, giving you memory safety and modern language features.
Do I need nightly Rust?
No, for this guide stable Rust works. Some advanced features in rustacuda may require nightly, but the basic usage does not.
Can I use this on Windows?
Yes, but you need the MSVC build tools and Visual Studio installed. Also, ensure the CUDA Toolkit's bin directory is in your PATH.
How do I pass arrays of custom structs to a kernel?
You need to define the struct in both Rust and CUDA C with the same memory layout (e.g., using #[repr(C)] in Rust). Then pass a pointer to the device buffer.
What if my GPU is not detected?
Run nvidia-smi. If it fails, install the NVIDIA driver. If it shows no GPU, your GPU might be too old or not supported by the CUDA version you installed.