Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Rust CUDA Setup: Compile Your First GPU Kernel

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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 nvcc compiler 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

  1. Verify CUDA installation – Run nvcc --version in a terminal. If it fails, reinstall the CUDA Toolkit and ensure the bin directory is in your PATH. Also run nvidia-smi to confirm your GPU is detected.
  2. Install Rust – If you haven't already, install Rust via rustup. Use the default stable toolchain. Verify with rustc --version.
  3. Create a new Rust project – Run cargo new rust_cuda_example and enter the directory: cd rust_cuda_example.
  4. Add dependencies – Edit Cargo.toml and add the following under [dependencies]:
    rustacuda = "0.2"
    rustacuda_derive = "0.2"
    These crates provide safe wrappers for CUDA. For a more low-level approach, you could use cuda-sys, but we'll stick with rustacuda.
  5. Write the kernel – Create a file named kernel.cu in 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:
    extern "C" __global__ void add_one(float *data, int n) {
        int idx = blockIdx.x * blockDim.x + threadIdx.x;
        if (idx < n) {
            data[idx] += 1.0f;
        }
    }
    The extern "C" is important so the symbol name is not mangled.
  6. Compile the kernel to PTX – Use nvcc to compile the kernel to PTX (a portable intermediate representation). Run:
    nvcc --ptx -o kernel.ptx kernel.cu
    This generates kernel.ptx in the same folder. If you get errors, ensure CUDA is correctly installed.
  7. Write the Rust host code – Replace the contents of src/main.rs with the following:
    use 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(())
    }
    Note: The unsafe block is required because launching a kernel is unsafe in the wrapper.
  8. Run the project – In the terminal, run cargo run. If everything is set up correctly, you should see Result: [1.0, 1.0, ...] (all ones).

Common Mistakes

  • Forgetting to compile the kernel to PTX – The Rust program expects a kernel.ptx file. If you skip step 6, you'll get a file-not-found error.
  • Using the wrong CUDA version – The rustacuda crate requires CUDA 10.0+. If you have an older version, you'll see linking errors. Check with nvcc --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 --release for 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 with map_err for debugging.
  • For larger projects, consider using rustacuda_core directly 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 sure kernel.ptx is in the same directory as your executable (or adjust the path in Module::load_from_file).
  • Linker errors about cudart – This usually means the CUDA library path is not set. On Linux, add export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH to 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 run nvcc from 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.