CUDA Tutorials for Deep Learning, RL and Libraries¶
Moving from foundational GPU kernels to real AI workloads means fusing operations to avoid memory round-trips, tiling spatial neighbourhoods into shared memory, and running entire agent populations in parallel on the device. This section walks through four complete CUDA C++ tutorials covering fused scaled dot-product attention, tiled 2D convolution, GPU-accelerated Q-learning, and NVIDIA's official math libraries (cuBLAS, cuFFT, cuRAND, cuSPARSE, cuSOLVER, and Thrust).
How to Compile and Run¶
- Tutorials 16, 17, and 19 are standalone
.cufiles that compile cleanly withnvccand require no extra linker flags. Tutorial 19 uses<curand_kernel.h>, which is the header-only device API for cuRAND, so it compiles as a single file as well.
nvcc 16.attentionKernelFusion.cu -o attention && ./attention
nvcc 17.efficientConvolution.cu -o convolution && ./convolution
nvcc 19.reinforcementLearning.cu -o rl && ./rl
- Tutorial 20 exercises NVIDIA's host-callable math libraries, so you must link each library explicitly when invoking
nvcc. Thrust is header-only and ships with the CUDA Toolkit, so it needs no extra flag.
nvcc 20.CUDALibraries.cu -o cudaLibraries -lcublas -lcufft -lcurand -lcusparse -lcusolver && ./cudaLibraries
- If you do not have a local NVIDIA GPU, every tutorial runs smoothly on a free Google Colab T4 instance. Switch the Colab runtime to T4 GPU, write a
.cufile into the notebook filesystem with%%writefile, and compile and run it with!nvcc.
- For Tutorial 20 on Google Colab, use the same
%%writefile cudaLibraries.cuworkflow and append the five library linker flags (-lcublas -lcufft -lcurand -lcusparse -lcusolver) to the!nvcccommand.
Fused Scaled Dot-Product Attention (Tutorial 16)¶
- Scaled dot-product attention is the computational heart of every Transformer, defined as
\[\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^\top}{\sqrt{d_k}}\right)V\]
- A naive GPU implementation launches a separate kernel for each stage (the \(QK^\top\) matrix product, scaling by \(1 / \sqrt{d_k}\), exponentiation, row-wise summation, division to normalise probabilities, and finally multiplying by \(V\)). Every extra kernel launch forces the GPU to write large intermediate tensors out to slow global memory (HBM) and immediately read them back in the next kernel.
- Kernel fusion collapses all of those stages into a single CUDA kernel so intermediate values stay on-chip in registers and shared memory. This cuts both kernel launch overhead and global memory traffic, which is where attention spends most of its time.
- Inside
fusedScaledDotProductAttention, each thread handles one(row, col)position inside a16 x 16thread block. It computes the dot product across the embedding dimension, divides bysqrtf(static_cast<float>(dim)), appliesexpf, and stores the result in the per-block shared arrayexpValues[BLOCK_SIZE][BLOCK_SIZE]. - Because every thread in a row of the block contributes to the same softmax denominator, the kernel uses
atomicAdd(&sumOfExponents[threadIdx.y], expValue)to safely accumulate the sum of exponentials in shared memory without race conditions. - Two
__syncthreads()barriers keep the block coordinated. The first ensures thread 0 has zero-initialisedsumOfExponentsbefore any thread callsatomicAdd, and the second ensures the full sum is ready before threads divide to formsoftmaxValueand accumulate the weighted sum againstV. - Keep in mind that this compact didactic kernel accumulates
sumOfExponentsper16 x 16block and omits the max-subtraction shift used for floating-point stability. Production kernels such as FlashAttention build directly on this same fusion philosophy, adding tiled online softmax across blocks and tracking a running maximum so exponentials never overflow. - Full source file 16.attentionKernelFusion.cu.
#include <cuda_runtime.h>
#include <random>
#include <vector>
#include <cmath>
#include <iostream>
const int BLOCK_SIZE = 16;
__global__ void fusedScaledDotProductAttention(
const float* Q,
const float* K,
const float* V,
float* attention,
int sequenceLength,
int dim
) {
int row = blockIdx.y * blockDim.y + threadIdx.y;
int col = blockIdx.x * blockDim.x + threadIdx.x;
__shared__ float expValues[BLOCK_SIZE][BLOCK_SIZE];
__shared__ float sumOfExponents[BLOCK_SIZE];
if (threadIdx.x == 0) {
sumOfExponents[threadIdx.y] = 0.0f;
}
__syncthreads();
if (row < sequenceLength && col < dim) {
float dotProduct = 0.0f;
// Compute the dot product Q * K^T
for (int idx = 0; idx < dim; ++idx) {
dotProduct += Q[row * dim + idx] * K[idx * sequenceLength + col];
}
// Scale the dot product
dotProduct /= sqrtf(static_cast<float>(dim));
// Apply exponential function
float expValue = expf(dotProduct);
expValues[threadIdx.y][threadIdx.x] = expValue;
// Accumulate the sum of exponentials
atomicAdd(&sumOfExponents[threadIdx.y], expValue);
}
__syncthreads();
if (row < sequenceLength && col < dim) {
// Normalize the exponentiated values
float softmaxValue = expValues[threadIdx.y][threadIdx.x] / sumOfExponents[threadIdx.y];
// Compute the final attention value
float finalValue = 0.0f;
for (int idx = 0; idx < dim; ++idx) {
finalValue += softmaxValue * V[idx * sequenceLength + col];
}
// Store the final attention value
attention[row * dim + col] = finalValue;
}
}
void fillMatrix(float* matrix, int rows, int cols) {
for (int row = 0; row < rows; ++row) {
for (int col = 0; col < cols; ++col) {
matrix[row * cols + col] = static_cast<float>(rand()) / RAND_MAX;
}
}
}
int main() {
int sequenceLength = 512;
int dim = 1024;
size_t size = sequenceLength * dim * sizeof(float);
float *queryProjection, *keyProjection, *valueProjection, *attention;
cudaMalloc(&queryProjection, size);
cudaMalloc(&keyProjection, size);
cudaMalloc(&valueProjection, size);
cudaMalloc(&attention, size);
// Create host arrays and fill them
float *hostQueryProjection = (float*)malloc(size);
float *hostKeyProjection = (float*)malloc(size);
float *hostValueProjection = (float*)malloc(size);
fillMatrix(hostQueryProjection, sequenceLength, dim);
fillMatrix(hostKeyProjection, sequenceLength, dim);
fillMatrix(hostValueProjection, sequenceLength, dim);
// Copy data from host to device
cudaMemcpy(queryProjection, hostQueryProjection, size, cudaMemcpyHostToDevice);
cudaMemcpy(keyProjection, hostKeyProjection, size, cudaMemcpyHostToDevice);
cudaMemcpy(valueProjection, hostValueProjection, size, cudaMemcpyHostToDevice);
// Calculate grid and block dimensions
dim3 blockDim(BLOCK_SIZE, BLOCK_SIZE);
dim3 gridDim((dim + BLOCK_SIZE - 1) / BLOCK_SIZE, (sequenceLength + BLOCK_SIZE - 1) / BLOCK_SIZE);
// Launch the kernel
fusedScaledDotProductAttention<<<gridDim, blockDim>>>(
queryProjection,
keyProjection,
valueProjection,
attention,
sequenceLength,
dim
);
// Check for errors
cudaError_t cudaStatus = cudaGetLastError();
if (cudaStatus != cudaSuccess) {
std::cerr << "Kernel launch failed: " << cudaGetErrorString(cudaStatus) << std::endl;
}
// Wait for GPU to finish before accessing on host
cudaDeviceSynchronize();
// Free device memory
cudaFree(queryProjection);
cudaFree(keyProjection);
cudaFree(valueProjection);
cudaFree(attention);
// Free host memory
free(hostQueryProjection);
free(hostKeyProjection);
free(hostValueProjection);
return 0;
}
// src/main.rs — build and run with: cargo oxide run --release
use cuda_core::{CudaContext, DeviceBuffer, LaunchConfig};
use cuda_device::{SharedArray, cuda_module, kernel, thread};
const BLOCK_SIZE: usize = 16;
#[cuda_module]
mod kernels {
use super::*;
#[kernel]
pub fn fused_scaled_dot_product_attention(
q: &[f32],
k: &[f32],
v: &[f32],
attention: &mut [f32],
sequence_length: usize,
dim: usize,
) {
let tx = thread::threadIdx_x() as usize;
let ty = thread::threadIdx_y() as usize;
let row = (thread::blockIdx_y() * thread::blockDim_y()) as usize + ty;
let col = (thread::blockIdx_x() * thread::blockDim_x()) as usize + tx;
static mut EXP_VALUES: SharedArray<f32, { BLOCK_SIZE * BLOCK_SIZE }> = SharedArray::UNINIT;
static mut SUM_OF_EXPONENTS: SharedArray<f32, BLOCK_SIZE> = SharedArray::UNINIT;
unsafe { EXP_VALUES[ty * BLOCK_SIZE + tx] = 0.0 };
if tx == 0 {
unsafe { SUM_OF_EXPONENTS[ty] = 0.0 };
}
thread::sync_threads();
if row < sequence_length && col < dim {
let mut dot_product = 0.0f32;
for idx in 0..dim {
dot_product += q[row * dim + idx] * k[idx * sequence_length + col];
}
dot_product /= (dim as f32).sqrt();
unsafe { EXP_VALUES[ty * BLOCK_SIZE + tx] = dot_product.exp() };
}
thread::sync_threads();
// Accumulate row-wise sum of exponentials in shared memory
if tx == 0 {
let mut row_sum = 0.0f32;
for j in 0..BLOCK_SIZE {
row_sum += unsafe { EXP_VALUES[ty * BLOCK_SIZE + j] };
}
unsafe { SUM_OF_EXPONENTS[ty] = row_sum };
}
thread::sync_threads();
if row < sequence_length && col < dim {
let softmax_val = unsafe { EXP_VALUES[ty * BLOCK_SIZE + tx] / SUM_OF_EXPONENTS[ty] };
let mut final_val = 0.0f32;
for idx in 0..dim {
final_val += softmax_val * v[idx * sequence_length + col];
}
attention[row * dim + col] = final_val;
}
}
}
fn fill_matrix(len: usize, state: &mut u64) -> Vec<f32> {
(0..len)
.map(|_| {
*state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
((*state >> 33) as f32) / (u32::MAX as f32)
})
.collect()
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let sequence_length = 512usize;
let dim = 1024usize;
let len = sequence_length * dim;
let mut rng = 42u64;
let h_q = fill_matrix(len, &mut rng);
let h_k = fill_matrix(len, &mut rng);
let h_v = fill_matrix(len, &mut rng);
let ctx = CudaContext::new(0)?;
let stream = ctx.default_stream();
let module = kernels::load(&ctx)?;
let d_q = DeviceBuffer::from_host(&stream, &h_q)?;
let d_k = DeviceBuffer::from_host(&stream, &h_k)?;
let d_v = DeviceBuffer::from_host(&stream, &h_v)?;
let mut d_attention = DeviceBuffer::<f32>::zeroed(&stream, len)?;
let cfg = LaunchConfig {
grid_dim: (
dim.div_ceil(BLOCK_SIZE) as u32,
sequence_length.div_ceil(BLOCK_SIZE) as u32,
1,
),
block_dim: (BLOCK_SIZE as u32, BLOCK_SIZE as u32, 1),
shared_mem_bytes: 0,
};
unsafe {
module.fused_scaled_dot_product_attention(
&stream,
cfg,
&d_q,
&d_k,
&d_v,
&mut d_attention,
sequence_length,
dim,
)?;
}
stream.synchronize()?;
Ok(())
}
Efficient Tiled 2D Convolution (Tutorial 17)¶
- 2D convolution slides a small filter (here
3 x 3) across an input feature map (here1024 x 1024) to produce an output feature map. In a naive CUDA kernel where each thread computes one output pixel directly from global memory, every thread loads all 9 pixels of its3 x 3neighbourhood independently, meaning interior pixels are fetched from HBM up to 9 times by neighbouring threads. - Shared memory tiling eliminates that redundant traffic. A
16 x 16thread block collaboratively loads a slightly larger input patch of size(TILE_SIZE + KERNEL_SIZE - 1) x (TILE_SIZE + KERNEL_SIZE - 1)(an18 x 18tile) into on-chip__shared__memory once, then every thread reads its3 x 3window at shared-memory speed. - Halo regions are the extra border pixels surrounding the core
16 x 16tile that edge threads need when centring the filter over their output pixels. In this kernel, every thread loads its main tile pixel first, and subsets of threads then load the right halo, the bottom halo, and the bottom-right corner halo, inserting0.0fzero-padding whenever a coordinate falls outside the input image bounds. - After
__syncthreads()guarantees the entire18 x 18patch is populated, the inner loop stacks three more classic GPU optimisations. The accumulatorsumlives in a thread-private register, adjacent threads read contiguous addresses for memory coalescing, and#pragma unrolltellsnvccto fully unroll the fixed3 x 3multiply-accumulate loops so there is zero branch or loop-counter overhead. - On the host side,
main()measures pure GPU execution time using hardwarecudaEvent_ttimestamps (cudaEventRecord,cudaEventSynchronize, andcudaEventElapsedTime), which is much more accurate than CPU wall-clock timers because kernel launches are asynchronous. - Full source file 17.efficientConvolution.cu.
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include <iostream>
#include <random>
#include <vector>
#include <cmath>
const int TILE_SIZE = 16; // Tile size for shared memory optimization
const int KERNEL_SIZE = 3; // Fixed kernel size (3x3)
// Efficient convolution kernel using shared memory
__global__ void efficientConvolution2D(
const float* input,
const float* kernel,
float* output,
int inputWidth,
int inputHeight,
int outputWidth,
int outputHeight
) {
// Calculate output coordinates
int outX = blockIdx.x * blockDim.x + threadIdx.x;
int outY = blockIdx.y * blockDim.y + threadIdx.y;
// Shared memory for input tile
__shared__ float sharedInput[TILE_SIZE + KERNEL_SIZE - 1][TILE_SIZE + KERNEL_SIZE - 1];
// Calculate input coordinates for this tile
int inX = outX - KERNEL_SIZE/2;
int inY = outY - KERNEL_SIZE/2;
// Load input tile into shared memory
int sharedX = threadIdx.x;
int sharedY = threadIdx.y;
// Each thread loads one element into shared memory
// Main tile
if (sharedX < TILE_SIZE && sharedY < TILE_SIZE) {
// Boundary check
if (inX >= 0 && inX < inputWidth && inY >= 0 && inY < inputHeight) {
sharedInput[sharedY][sharedX] = input[inY * inputWidth + inX];
} else {
sharedInput[sharedY][sharedX] = 0.0f; // Zero padding
}
}
// Load halo regions (additional threads load the border elements)
if (sharedX < KERNEL_SIZE - 1 && sharedY < TILE_SIZE) {
// Right halo
int haloX = inX + TILE_SIZE;
if (haloX < inputWidth && inY >= 0 && inY < inputHeight) {
sharedInput[sharedY][sharedX + TILE_SIZE] = input[inY * inputWidth + haloX];
} else {
sharedInput[sharedY][sharedX + TILE_SIZE] = 0.0f; // Zero padding
}
}
if (sharedX < TILE_SIZE && sharedY < KERNEL_SIZE - 1) {
// Bottom halo
int haloY = inY + TILE_SIZE;
if (inX >= 0 && inX < inputWidth && haloY < inputHeight) {
sharedInput[sharedY + TILE_SIZE][sharedX] = input[haloY * inputWidth + inX];
} else {
sharedInput[sharedY + TILE_SIZE][sharedX] = 0.0f; // Zero padding
}
}
if (sharedX < KERNEL_SIZE - 1 && sharedY < KERNEL_SIZE - 1) {
// Bottom-right corner halo
int haloX = inX + TILE_SIZE;
int haloY = inY + TILE_SIZE;
if (haloX < inputWidth && haloY < inputHeight) {
sharedInput[sharedY + TILE_SIZE][sharedX + TILE_SIZE] = input[haloY * inputWidth + haloX];
} else {
sharedInput[sharedY + TILE_SIZE][sharedX + TILE_SIZE] = 0.0f; // Zero padding
}
}
// Ensure all threads have loaded the shared memory
__syncthreads();
// Compute convolution if within output bounds
if (outX < outputWidth && outY < outputHeight) {
float sum = 0.0f;
// Unrolled loop for 3x3 kernel for better performance
#pragma unroll
for (int ky = 0; ky < KERNEL_SIZE; ky++) {
#pragma unroll
for (int kx = 0; kx < KERNEL_SIZE; kx++) {
sum += sharedInput[threadIdx.y + ky][threadIdx.x + kx] *
kernel[ky * KERNEL_SIZE + kx];
}
}
// Write result to output
output[outY * outputWidth + outX] = sum;
}
}
// Helper function to fill matrix with random values
void fillMatrix(float* matrix, int size) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<float> dis(-1.0f, 1.0f);
for (int i = 0; i < size; i++) {
matrix[i] = dis(gen);
}
}
int main() {
// Define input dimensions
int inputWidth = 1024;
int inputHeight = 1024;
int kernelSize = KERNEL_SIZE;
// Calculate output dimensions
int outputWidth = inputWidth - kernelSize + 1;
int outputHeight = inputHeight - kernelSize + 1;
// Allocate host memory
std::vector<float> hostInput(inputWidth * inputHeight);
std::vector<float> hostKernel(kernelSize * kernelSize);
std::vector<float> hostOutput(outputWidth * outputHeight);
// Fill input and kernel with random data
fillMatrix(hostInput.data(), inputWidth * inputHeight);
fillMatrix(hostKernel.data(), kernelSize * kernelSize);
// Allocate device memory
float *deviceInput, *deviceKernel, *deviceOutput;
cudaMalloc(&deviceInput, inputWidth * inputHeight * sizeof(float));
cudaMalloc(&deviceKernel, kernelSize * kernelSize * sizeof(float));
cudaMalloc(&deviceOutput, outputWidth * outputHeight * sizeof(float));
// Copy data from host to device
cudaMemcpy(deviceInput, hostInput.data(), inputWidth * inputHeight * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(deviceKernel, hostKernel.data(), kernelSize * kernelSize * sizeof(float), cudaMemcpyHostToDevice);
// Define grid and block dimensions
dim3 blockDim(TILE_SIZE, TILE_SIZE);
dim3 gridDim((outputWidth + TILE_SIZE - 1) / TILE_SIZE,
(outputHeight + TILE_SIZE - 1) / TILE_SIZE);
// Launch kernel with timing
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);
cudaEventRecord(start);
efficientConvolution2D<<<gridDim, blockDim>>>(
deviceInput,
deviceKernel,
deviceOutput,
inputWidth,
inputHeight,
outputWidth,
outputHeight
);
cudaEventRecord(stop);
// Wait for kernel to finish
cudaEventSynchronize(stop);
// Calculate elapsed time
float milliseconds = 0;
cudaEventElapsedTime(&milliseconds, start, stop);
// Copy result back to host
cudaMemcpy(hostOutput.data(), deviceOutput, outputWidth * outputHeight * sizeof(float), cudaMemcpyDeviceToHost);
// Print timing information
std::cout << "Convolution completed in " << milliseconds << " ms" << std::endl;
std::cout << "Input size: " << inputWidth << "x" << inputHeight << std::endl;
std::cout << "Kernel size: " << kernelSize << "x" << kernelSize << std::endl;
std::cout << "Output size: " << outputWidth << "x" << outputHeight << std::endl;
// Print a small portion of the output for verification
std::cout << "\nSample output values:" << std::endl;
for (int i = 0; i < 5 && i < outputHeight; i++) {
for (int j = 0; j < 5 && j < outputWidth; j++) {
std::cout << hostOutput[i * outputWidth + j] << " ";
}
std::cout << std::endl;
}
// Free device memory
cudaFree(deviceInput);
cudaFree(deviceKernel);
cudaFree(deviceOutput);
// Destroy CUDA events
cudaEventDestroy(start);
cudaEventDestroy(stop);
return 0;
}
// src/main.rs — build and run with: cargo oxide run --release
use cuda_core::{CudaContext, DeviceBuffer, LaunchConfig};
use cuda_device::{SharedArray, cuda_module, kernel, thread};
use std::time::Instant;
const TILE_SIZE: usize = 16;
const KERNEL_SIZE: usize = 3;
const SHARED_DIM: usize = TILE_SIZE + KERNEL_SIZE - 1;
#[cuda_module]
mod kernels {
use super::*;
#[kernel]
pub fn efficient_convolution_2d(
input: &[f32],
filter: &[f32],
output: &mut [f32],
input_w: usize,
input_h: usize,
output_w: usize,
output_h: usize,
) {
let sx = thread::threadIdx_x() as usize;
let sy = thread::threadIdx_y() as usize;
let out_x = (thread::blockIdx_x() * thread::blockDim_x()) as usize + sx;
let out_y = (thread::blockIdx_y() * thread::blockDim_y()) as usize + sy;
static mut SHARED_INPUT: SharedArray<f32, { SHARED_DIM * SHARED_DIM }> =
SharedArray::UNINIT;
let in_x = out_x as isize - (KERNEL_SIZE / 2) as isize;
let in_y = out_y as isize - (KERNEL_SIZE / 2) as isize;
let load_clamped = |x: isize, y: isize| -> f32 {
if x >= 0 && (x as usize) < input_w && y >= 0 && (y as usize) < input_h {
input[y as usize * input_w + x as usize]
} else {
0.0
}
};
// Main tile
if sx < TILE_SIZE && sy < TILE_SIZE {
unsafe { SHARED_INPUT[sy * SHARED_DIM + sx] = load_clamped(in_x, in_y) };
}
// Right halo
if sx < KERNEL_SIZE - 1 && sy < TILE_SIZE {
unsafe {
SHARED_INPUT[sy * SHARED_DIM + (sx + TILE_SIZE)] =
load_clamped(in_x + TILE_SIZE as isize, in_y);
}
}
// Bottom halo
if sx < TILE_SIZE && sy < KERNEL_SIZE - 1 {
unsafe {
SHARED_INPUT[(sy + TILE_SIZE) * SHARED_DIM + sx] =
load_clamped(in_x, in_y + TILE_SIZE as isize);
}
}
// Bottom-right corner halo
if sx < KERNEL_SIZE - 1 && sy < KERNEL_SIZE - 1 {
unsafe {
SHARED_INPUT[(sy + TILE_SIZE) * SHARED_DIM + (sx + TILE_SIZE)] =
load_clamped(in_x + TILE_SIZE as isize, in_y + TILE_SIZE as isize);
}
}
thread::sync_threads();
if out_x < output_w && out_y < output_h {
let mut sum = 0.0f32;
for ky in 0..KERNEL_SIZE {
for kx in 0..KERNEL_SIZE {
let pixel = unsafe { SHARED_INPUT[(sy + ky) * SHARED_DIM + (sx + kx)] };
sum += pixel * filter[ky * KERNEL_SIZE + kx];
}
}
output[out_y * output_w + out_x] = sum;
}
}
}
fn fill_uniform(len: usize, state: &mut u64) -> Vec<f32> {
(0..len)
.map(|_| {
*state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
2.0 * (((*state >> 33) as f32) / (u32::MAX as f32)) - 1.0
})
.collect()
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let (input_w, input_h) = (1024usize, 1024usize);
let output_w = input_w - KERNEL_SIZE + 1;
let output_h = input_h - KERNEL_SIZE + 1;
let mut rng = 42u64;
let host_input = fill_uniform(input_w * input_h, &mut rng);
let host_kernel = fill_uniform(KERNEL_SIZE * KERNEL_SIZE, &mut rng);
let ctx = CudaContext::new(0)?;
let stream = ctx.default_stream();
let module = kernels::load(&ctx)?;
let d_input = DeviceBuffer::from_host(&stream, &host_input)?;
let d_kernel = DeviceBuffer::from_host(&stream, &host_kernel)?;
let mut d_output = DeviceBuffer::<f32>::zeroed(&stream, output_w * output_h)?;
let cfg = LaunchConfig {
grid_dim: (
output_w.div_ceil(TILE_SIZE) as u32,
output_h.div_ceil(TILE_SIZE) as u32,
1,
),
block_dim: (TILE_SIZE as u32, TILE_SIZE as u32, 1),
shared_mem_bytes: 0,
};
let start = Instant::now();
unsafe {
module.efficient_convolution_2d(
&stream,
cfg,
&d_input,
&d_kernel,
&mut d_output,
input_w,
input_h,
output_w,
output_h,
)?;
}
stream.synchronize()?;
let ms = start.elapsed().as_secs_f64() * 1000.0;
let host_output = d_output.to_host_vec(&stream)?;
println!("Convolution completed in {ms:.3} ms");
println!("Input size: {input_w}x{input_h}");
println!("Kernel size: {KERNEL_SIZE}x{KERNEL_SIZE}");
println!("Output size: {output_w}x{output_h}");
println!("
Sample output values:");
for i in 0..5.min(output_h) {
for j in 0..5.min(output_w) {
print!("{:.4} ", host_output[i * output_w + j]);
}
println!();
}
Ok(())
}
GPU-Accelerated Q-Learning (Tutorial 19)¶
- Reinforcement learning is notoriously sample-hungry because an agent learns only by interacting with its environment step after step. Moving both the environment simulation and the learning update onto the GPU lets hundreds or thousands of agents explore simultaneously, which is the exact idea behind modern GPU-native RL simulators such as Isaac Gym and MJX.
- This tutorial models a
10 x 10grid world with 10 randomly placed obstacles, four discrete actions (Up, Down, Left, Right), a+1.0reward for reaching the bottom-right goal(9, 9), a-1.0penalty for bumping into an obstacle (leaving the agent in place), and a-0.01step penalty to encourage shortest paths. - All
128parallel agents share a single Q-table on the GPU and update it via the classic temporal-difference rule
\[Q(s, a) \leftarrow Q(s, a) + \alpha \left( r + \gamma \max_{a'} Q(s', a') - Q(s, a) \right)\]
- Parallelisation splits cleanly across four focused kernels, with one GPU thread mapped to each agent.
setupCurandinitialises an independentcurandStatestream per thread so every agent generates uncorrelated random numbers directly on the device.selectActionsexecutes an \(\epsilon\)-greedy policy in parallel, picking a uniform random action with probability \(\epsilon\) and otherwise scanning the four Q-values of the agent's current state to exploit the highest-value move.simulateStepadvances every active agent by one grid move, checks for obstacle collisions and goal arrival, and writesnext_states,rewards, anddonesin parallel.updateQValuescomputes \(\max_{a'} Q(s', a')\) and writes the updated Q-value back to global memory for every active agent.- Across
1,000episodes, \(\epsilon\) decays exponentially from1.0down to0.01, smoothly shifting the population from broad exploration to exploitation. At the end, the host copies the learned Q-table back and prints a grid visualisation showing the maximum Q-value in every cell alongside obstacles (X) and the goal (G). - Because multiple agents may occasionally update the same
(state, action)entry in the same step without locks, this demo performs unsynchronised ("Hogwild"-style) updates, which work well for tabular Q-learning and avoid atomic contention. - Full source file 19.reinforcementLearning.cu.
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include <curand_kernel.h>
#include <iostream>
#include <vector>
#include <random>
#include <iomanip>
#include <chrono>
// Constants for Q-learning
const int GRID_SIZE = 10; // Size of the grid world (GRID_SIZE x GRID_SIZE)
const int NUM_ACTIONS = 4; // Number of possible actions (Up, Down, Left, Right)
const int NUM_STATES = GRID_SIZE * GRID_SIZE; // Number of states in the environment
const int MAX_EPISODES = 1000; // Maximum number of episodes to run
const int MAX_STEPS = 100; // Maximum steps per episode
const int NUM_PARALLEL_AGENTS = 128; // Number of parallel agents to simulate
const float ALPHA = 0.1f; // Learning rate
const float GAMMA = 0.99f; // Discount factor
const float EPSILON_START = 1.0f; // Initial exploration rate
const float EPSILON_END = 0.01f; // Final exploration rate
const float EPSILON_DECAY = 0.995f; // Decay rate for exploration
// Environment constants
const int GOAL_X = GRID_SIZE - 1;
const int GOAL_Y = GRID_SIZE - 1;
const int NUM_OBSTACLES = 10; // Number of obstacles in the grid
// CUDA random number generation setup
__global__ void setupCurand(curandState *state, unsigned long seed) {
int idx = threadIdx.x + blockIdx.x * blockDim.x;
if (idx < NUM_PARALLEL_AGENTS) {
curand_init(seed, idx, 0, &state[idx]);
}
}
// GPU kernel for epsilon-greedy action selection
__global__ void selectActions(
float *Q_table,
int *states,
int *actions,
float epsilon,
curandState *curandState
) {
int agentIdx = threadIdx.x + blockIdx.x * blockDim.x;
if (agentIdx < NUM_PARALLEL_AGENTS) {
// Get random value for epsilon-greedy policy
float random_val = curand_uniform(&curandState[agentIdx]);
// Current state of the agent
int state = states[agentIdx];
int action;
// Epsilon-greedy policy
if (random_val < epsilon) {
// Explore: choose random action
action = (int)(curand_uniform(&curandState[agentIdx]) * NUM_ACTIONS);
} else {
// Exploit: choose best action
float max_q_value = -FLT_MAX;
int best_action = 0;
for (int a = 0; a < NUM_ACTIONS; a++) {
float q_value = Q_table[state * NUM_ACTIONS + a];
if (q_value > max_q_value) {
max_q_value = q_value;
best_action = a;
}
}
action = best_action;
}
actions[agentIdx] = action;
}
}
// GPU kernel for environment step simulation
__global__ void simulateStep(
int *states,
int *actions,
int *next_states,
float *rewards,
bool *dones,
int *obstacles,
int numObstacles,
curandState *curandState
) {
int agentIdx = threadIdx.x + blockIdx.x * blockDim.x;
if (agentIdx < NUM_PARALLEL_AGENTS && !dones[agentIdx]) {
// Current state
int state = states[agentIdx];
int x = state % GRID_SIZE;
int y = state / GRID_SIZE;
// Execute action
int action = actions[agentIdx];
int new_x = x;
int new_y = y;
if (action == 0) new_y = max(0, y - 1); // Up
else if (action == 1) new_y = min(GRID_SIZE - 1, y + 1); // Down
else if (action == 2) new_x = max(0, x - 1); // Left
else if (action == 3) new_x = min(GRID_SIZE - 1, x + 1); // Right
// Check for obstacle collision
bool hit_obstacle = false;
for (int i = 0; i < numObstacles; i++) {
int obs_x = obstacles[i] % GRID_SIZE;
int obs_y = obstacles[i] / GRID_SIZE;
if (new_x == obs_x && new_y == obs_y) {
hit_obstacle = true;
break;
}
}
// Calculate reward and next state
float reward;
if (hit_obstacle) {
reward = -1.0f;
new_x = x; // Stay in place if hit obstacle
new_y = y;
} else if (new_x == GOAL_X && new_y == GOAL_Y) {
reward = 1.0f;
dones[agentIdx] = true;
} else {
reward = -0.01f; // Small penalty for each step
}
next_states[agentIdx] = new_y * GRID_SIZE + new_x;
rewards[agentIdx] = reward;
}
}
// GPU kernel for Q-table update
__global__ void updateQValues(
float *Q_table,
int *states,
int *actions,
int *next_states,
float *rewards,
bool *dones
) {
int agentIdx = threadIdx.x + blockIdx.x * blockDim.x;
if (agentIdx < NUM_PARALLEL_AGENTS && !dones[agentIdx]) {
int state = states[agentIdx];
int action = actions[agentIdx];
int next_state = next_states[agentIdx];
float reward = rewards[agentIdx];
// Find max Q-value for next state
float max_next_q = -FLT_MAX;
for (int a = 0; a < NUM_ACTIONS; a++) {
float q = Q_table[next_state * NUM_ACTIONS + a];
max_next_q = max(max_next_q, q);
}
// Q-learning update rule
float current_q = Q_table[state * NUM_ACTIONS + action];
float td_target = reward + GAMMA * max_next_q;
float new_q = current_q + ALPHA * (td_target - current_q);
Q_table[state * NUM_ACTIONS + action] = new_q;
}
}
// Host function to generate random obstacles
void generateObstacles(int *obstacles, int numObstacles) {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, NUM_STATES - 1);
for (int i = 0; i < numObstacles; i++) {
int obstacle = dis(gen);
// Make sure obstacles are not at start or goal
while (obstacle == 0 || obstacle == (GRID_SIZE * GRID_SIZE - 1)) {
obstacle = dis(gen);
}
obstacles[i] = obstacle;
}
}
// Visualization function for Q-table
void visualizeQTable(float *Q_table, int *obstacles, int numObstacles) {
std::cout << "\nQ-Table Visualization (Max Q-value per state):" << std::endl;
std::cout << "Goal is at position (" << GOAL_X << ", " << GOAL_Y << ")" << std::endl;
for (int y = 0; y < GRID_SIZE; y++) {
for (int x = 0; x < GRID_SIZE; x++) {
int state = y * GRID_SIZE + x;
// Check if this position is an obstacle
bool is_obstacle = false;
for (int i = 0; i < numObstacles; i++) {
if (obstacles[i] == state) {
is_obstacle = true;
break;
}
}
if (is_obstacle) {
std::cout << std::setw(6) << "X ";
} else if (x == GOAL_X && y == GOAL_Y) {
std::cout << std::setw(6) << "G ";
} else {
// Find max Q-value for this state
float max_q = -FLT_MAX;
for (int a = 0; a < NUM_ACTIONS; a++) {
max_q = std::max(max_q, Q_table[state * NUM_ACTIONS + a]);
}
std::cout << std::setw(6) << std::fixed << std::setprecision(2) << max_q << " ";
}
}
std::cout << std::endl;
}
}
int main() {
// Allocate host memory
float *h_Q_table = new float[NUM_STATES * NUM_ACTIONS]();
int *h_obstacles = new int[NUM_OBSTACLES];
// Generate random obstacles
generateObstacles(h_obstacles, NUM_OBSTACLES);
// Allocate device memory
float *d_Q_table;
int *d_states, *d_next_states, *d_actions, *d_obstacles;
float *d_rewards;
bool *d_dones;
curandState *d_curandState;
cudaMalloc((void**)&d_Q_table, NUM_STATES * NUM_ACTIONS * sizeof(float));
cudaMalloc((void**)&d_states, NUM_PARALLEL_AGENTS * sizeof(int));
cudaMalloc((void**)&d_next_states, NUM_PARALLEL_AGENTS * sizeof(int));
cudaMalloc((void**)&d_actions, NUM_PARALLEL_AGENTS * sizeof(int));
cudaMalloc((void**)&d_rewards, NUM_PARALLEL_AGENTS * sizeof(float));
cudaMalloc((void**)&d_dones, NUM_PARALLEL_AGENTS * sizeof(bool));
cudaMalloc((void**)&d_obstacles, NUM_OBSTACLES * sizeof(int));
cudaMalloc((void**)&d_curandState, NUM_PARALLEL_AGENTS * sizeof(curandState));
// Initialize Q-table and obstacles on device
cudaMemcpy(d_Q_table, h_Q_table, NUM_STATES * NUM_ACTIONS * sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_obstacles, h_obstacles, NUM_OBSTACLES * sizeof(int), cudaMemcpyHostToDevice);
// Initialize random states
int threadsPerBlock = 256;
int blocksPerGrid = (NUM_PARALLEL_AGENTS + threadsPerBlock - 1) / threadsPerBlock;
unsigned long seed = std::chrono::system_clock::now().time_since_epoch().count();
setupCurand<<<blocksPerGrid, threadsPerBlock>>>(d_curandState, seed);
// Start timing
auto start_time = std::chrono::high_resolution_clock::now();
// Main training loop
float epsilon = EPSILON_START;
int total_steps = 0;
for (int episode = 0; episode < MAX_EPISODES; episode++) {
// Reset agents to starting positions
std::vector<int> initial_states(NUM_PARALLEL_AGENTS, 0); // All agents start at (0,0)
std::vector<bool> initial_dones(NUM_PARALLEL_AGENTS, false);
cudaMemcpy(d_states, initial_states.data(), NUM_PARALLEL_AGENTS * sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_dones, initial_dones.data(), NUM_PARALLEL_AGENTS * sizeof(bool), cudaMemcpyHostToDevice);
int steps = 0;
bool all_done = false;
while (!all_done && steps < MAX_STEPS) {
// Select actions using epsilon-greedy policy
selectActions<<<blocksPerGrid, threadsPerBlock>>>(
d_Q_table, d_states, d_actions, epsilon, d_curandState
);
// Simulate one step for all agents
simulateStep<<<blocksPerGrid, threadsPerBlock>>>(
d_states, d_actions, d_next_states, d_rewards, d_dones,
d_obstacles, NUM_OBSTACLES, d_curandState
);
// Update Q-values
updateQValues<<<blocksPerGrid, threadsPerBlock>>>(
d_Q_table, d_states, d_actions, d_next_states, d_rewards, d_dones
);
// Copy next states to current states
cudaMemcpy(d_states, d_next_states, NUM_PARALLEL_AGENTS * sizeof(int), cudaMemcpyDeviceToDevice);
// Check if all agents are done
std::vector<bool> h_dones(NUM_PARALLEL_AGENTS);
cudaMemcpy(h_dones.data(), d_dones, NUM_PARALLEL_AGENTS * sizeof(bool), cudaMemcpyDeviceToHost);
all_done = true;
for (int i = 0; i < NUM_PARALLEL_AGENTS; i++) {
if (!h_dones[i]) {
all_done = false;
break;
}
}
steps++;
total_steps++;
}
// Decay epsilon
epsilon = std::max(EPSILON_END, epsilon * EPSILON_DECAY);
// Print progress every 100 episodes
if ((episode + 1) % 100 == 0) {
std::cout << "Episode " << episode + 1 << " completed. Epsilon: " << epsilon << std::endl;
}
}
// End timing
auto end_time = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time).count();
// Copy Q-table back to host
cudaMemcpy(h_Q_table, d_Q_table, NUM_STATES * NUM_ACTIONS * sizeof(float), cudaMemcpyDeviceToHost);
// Print results
std::cout << "\nTraining complete!" << std::endl;
std::cout << "Total steps: " << total_steps << std::endl;
std::cout << "Training time: " << duration << " ms" << std::endl;
// Visualize Q-table
visualizeQTable(h_Q_table, h_obstacles, NUM_OBSTACLES);
// Free device memory
cudaFree(d_Q_table);
cudaFree(d_states);
cudaFree(d_next_states);
cudaFree(d_actions);
cudaFree(d_rewards);
cudaFree(d_dones);
cudaFree(d_obstacles);
cudaFree(d_curandState);
// Free host memory
delete[] h_Q_table;
delete[] h_obstacles;
return 0;
}
// src/main.rs — build and run with: cargo oxide run --release
use cuda_core::{CudaContext, DeviceBuffer, LaunchConfig};
use cuda_device::{cuda_module, kernel, thread};
use std::time::Instant;
const GRID_SIZE: usize = 10;
const NUM_ACTIONS: usize = 4;
const NUM_STATES: usize = GRID_SIZE * GRID_SIZE;
const MAX_EPISODES: usize = 1000;
const MAX_STEPS: usize = 100;
const NUM_PARALLEL_AGENTS: usize = 128;
const ALPHA: f32 = 0.1;
const GAMMA: f32 = 0.99;
const EPSILON_START: f32 = 1.0;
const EPSILON_END: f32 = 0.01;
const EPSILON_DECAY: f32 = 0.995;
const GOAL_X: usize = GRID_SIZE - 1;
const GOAL_Y: usize = GRID_SIZE - 1;
const NUM_OBSTACLES: usize = 10;
#[cuda_module]
mod kernels {
use super::*;
#[inline(always)]
fn next_uniform_f32(state: &mut u64) -> f32 {
// XorShift64* per-agent PRNG on device
let mut x = *state;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
*state = x;
let bits = x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 40;
(bits as f32) / ((1u32 << 24) as f32)
}
#[kernel]
pub fn setup_rng(rng_states: &mut [u64], seed: u64) {
let idx = thread::index_1d().get();
if idx < NUM_PARALLEL_AGENTS {
rng_states[idx] = seed ^ ((idx as u64 + 1).wrapping_mul(0x9E37_79B9_7F4A_7C15));
}
}
#[kernel]
pub fn select_actions(
q_table: &[f32],
states: &[i32],
actions: &mut [i32],
epsilon: f32,
rng_states: &mut [u64],
) {
let agent = thread::index_1d().get();
if agent < NUM_PARALLEL_AGENTS {
let r = next_uniform_f32(&mut rng_states[agent]);
let state = states[agent] as usize;
let action = if r < epsilon {
((next_uniform_f32(&mut rng_states[agent]) * NUM_ACTIONS as f32) as usize)
.min(NUM_ACTIONS - 1) as i32
} else {
let mut max_q = f32::NEG_INFINITY;
let mut best = 0i32;
for a in 0..NUM_ACTIONS {
let q = q_table[state * NUM_ACTIONS + a];
if q > max_q {
max_q = q;
best = a as i32;
}
}
best
};
actions[agent] = action;
}
}
#[kernel]
pub fn simulate_step(
states: &[i32],
actions: &[i32],
next_states: &mut [i32],
rewards: &mut [f32],
dones: &mut [u8],
obstacles: &[i32],
) {
let agent = thread::index_1d().get();
if agent < NUM_PARALLEL_AGENTS && dones[agent] == 0 {
let state = states[agent] as usize;
let x = state % GRID_SIZE;
let y = state / GRID_SIZE;
let mut new_x = x;
let mut new_y = y;
match actions[agent] {
0 => new_y = y.saturating_sub(1), // Up
1 => new_y = (y + 1).min(GRID_SIZE - 1), // Down
2 => new_x = x.saturating_sub(1), // Left
3 => new_x = (x + 1).min(GRID_SIZE - 1), // Right
_ => {}
}
let mut hit_obstacle = false;
for &obs in obstacles {
let obs_u = obs as usize;
if new_x == obs_u % GRID_SIZE && new_y == obs_u / GRID_SIZE {
hit_obstacle = true;
break;
}
}
let reward = if hit_obstacle {
new_x = x;
new_y = y;
-1.0
} else if new_x == GOAL_X && new_y == GOAL_Y {
dones[agent] = 1;
1.0
} else {
-0.01
};
next_states[agent] = (new_y * GRID_SIZE + new_x) as i32;
rewards[agent] = reward;
}
}
#[kernel]
pub fn update_q_values(
q_table: &mut [f32],
states: &[i32],
actions: &[i32],
next_states: &[i32],
rewards: &[f32],
dones: &[u8],
) {
let agent = thread::index_1d().get();
if agent < NUM_PARALLEL_AGENTS && dones[agent] == 0 {
let state = states[agent] as usize;
let action = actions[agent] as usize;
let next_state = next_states[agent] as usize;
let reward = rewards[agent];
let mut max_next_q = f32::NEG_INFINITY;
for a in 0..NUM_ACTIONS {
let q = q_table[next_state * NUM_ACTIONS + a];
if q > max_next_q {
max_next_q = q;
}
}
let slot = state * NUM_ACTIONS + action;
let current_q = q_table[slot];
let td_target = reward + GAMMA * max_next_q;
q_table[slot] = current_q + ALPHA * (td_target - current_q);
}
}
}
fn generate_obstacles(seed: u64) -> Vec<i32> {
let mut state = seed;
let mut obstacles = Vec::with_capacity(NUM_OBSTACLES);
for _ in 0..NUM_OBSTACLES {
loop {
state = state.wrapping_mul(6364136223846793005).wrapping_add(1);
let cell = ((state >> 33) as usize % NUM_STATES) as i32;
if cell != 0 && cell != (NUM_STATES - 1) as i32 {
obstacles.push(cell);
break;
}
}
}
obstacles
}
fn visualize_q_table(q_table: &[f32], obstacles: &[i32]) {
println!("
Q-Table Visualization (Max Q-value per state):");
println!("Goal is at position ({GOAL_X}, {GOAL_Y})");
for y in 0..GRID_SIZE {
for x in 0..GRID_SIZE {
let state = (y * GRID_SIZE + x) as i32;
if obstacles.contains(&state) {
print!("{:>6} ", "X");
} else if x == GOAL_X && y == GOAL_Y {
print!("{:>6} ", "G");
} else {
let s = state as usize;
let max_q = (0..NUM_ACTIONS)
.map(|a| q_table[s * NUM_ACTIONS + a])
.fold(f32::NEG_INFINITY, f32::max);
print!("{max_q:>6.2} ");
}
}
println!();
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let h_obstacles = generate_obstacles(42);
let ctx = CudaContext::new(0)?;
let stream = ctx.default_stream();
let module = kernels::load(&ctx)?;
let mut d_q_table = DeviceBuffer::<f32>::zeroed(&stream, NUM_STATES * NUM_ACTIONS)?;
let mut d_states = DeviceBuffer::<i32>::zeroed(&stream, NUM_PARALLEL_AGENTS)?;
let mut d_next_states = DeviceBuffer::<i32>::zeroed(&stream, NUM_PARALLEL_AGENTS)?;
let mut d_actions = DeviceBuffer::<i32>::zeroed(&stream, NUM_PARALLEL_AGENTS)?;
let mut d_rewards = DeviceBuffer::<f32>::zeroed(&stream, NUM_PARALLEL_AGENTS)?;
let mut d_dones = DeviceBuffer::<u8>::zeroed(&stream, NUM_PARALLEL_AGENTS)?;
let d_obstacles = DeviceBuffer::from_host(&stream, &h_obstacles)?;
let mut d_rng = DeviceBuffer::<u64>::zeroed(&stream, NUM_PARALLEL_AGENTS)?;
let cfg = LaunchConfig::for_num_elems(NUM_PARALLEL_AGENTS as u32);
unsafe { module.setup_rng(&stream, cfg, &mut d_rng, 12345u64)? };
let start_time = Instant::now();
let mut epsilon = EPSILON_START;
let mut total_steps = 0usize;
let zero_states = vec![0i32; NUM_PARALLEL_AGENTS];
let zero_dones = vec![0u8; NUM_PARALLEL_AGENTS];
for episode in 0..MAX_EPISODES {
d_states.copy_from_host(&stream, &zero_states)?;
d_dones.copy_from_host(&stream, &zero_dones)?;
for _step in 0..MAX_STEPS {
unsafe {
module.select_actions(&stream, cfg, &d_q_table, &d_states, &mut d_actions, epsilon, &mut d_rng)?;
module.simulate_step(
&stream, cfg, &d_states, &d_actions, &mut d_next_states, &mut d_rewards, &mut d_dones, &d_obstacles,
)?;
module.update_q_values(
&stream, cfg, &mut d_q_table, &d_states, &d_actions, &d_next_states, &d_rewards, &d_dones,
)?;
}
d_states.copy_from_device(&stream, &d_next_states)?;
total_steps += 1;
if d_dones.to_host_vec(&stream)?.iter().all(|&done| done != 0) {
break;
}
}
epsilon = EPSILON_END.max(epsilon * EPSILON_DECAY);
if (episode + 1) % 100 == 0 {
println!("Episode {} completed. Epsilon: {epsilon:.4}", episode + 1);
}
}
let h_q_table = d_q_table.to_host_vec(&stream)?;
println!("
Training complete!");
println!("Total steps: {total_steps}");
println!("Training time: {} ms", start_time.elapsed().as_millis());
visualize_q_table(&h_q_table, &h_obstacles);
Ok(())
}
Official CUDA Math and Parallel Libraries (Tutorial 20)¶
- Knowing how to write raw CUDA kernels is essential for custom fused operations, yet for standard linear algebra, signal processing, random sampling, sparse maths, linear solvers, and parallel sorting you should almost always reach for NVIDIA's official libraries first. They are heavily tuned per GPU generation with Tensor Core pipelines, warp-level intrinsics, and optimal tiling strategies that are extremely difficult to match by hand.
- Full runnable source file 20.CUDALibraries.cu. Below, the file is split cleanly into its shared setup, each of the six library demonstrations, and the
main()runner.
nvcc 20.CUDALibraries.cu -o cudaLibraries -lcublas -lcufft -lcurand -lcusparse -lcusolver && ./cudaLibraries
Shared Headers and Error-Checking Helpers¶
- Every CUDA API call returns a
cudaError_tstatus code. Wrapping allocations and copies in aCHECK_CUDA_ERRORmacro catches silent failures immediately with the exact file name and line number, whileprintMatrixformats small matrices cleanly on the host for inspection.
#include <cuda_runtime.h>
#include <device_launch_parameters.h>
#include <iostream>
#include <iomanip>
#include <vector>
#include <cmath>
#include <cufft.h> // CUDA FFT library
#include <cublas_v2.h> // CUDA BLAS library
#include <curand.h> // CUDA random number generation library
#include <cusparse.h> // CUDA sparse matrix library
#include <cusolverDn.h> // CUDA solver library
#include <thrust/device_vector.h> // Thrust template library
#include <thrust/sort.h>
#include <thrust/reduce.h>
#include <thrust/functional.h>
// Error checking macro for CUDA calls
#define CHECK_CUDA_ERROR(val) checkCudaError((val), #val, __FILE__, __LINE__)
inline void checkCudaError(cudaError_t result, const char* func, const char* file, int line) {
if (result != cudaSuccess) {
std::cerr << "CUDA error at " << file << ":" << line << " code=" << static_cast<unsigned int>(result)
<< " \"" << func << "\" \n" << cudaGetErrorString(result) << std::endl;
exit(EXIT_FAILURE);
}
}
// Print formatted matrix for display
void printMatrix(const float* matrix, int rows, int cols, const char* name) {
std::cout << "Matrix " << name << " (" << rows << "x" << cols << "):" << std::endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
std::cout << std::setw(10) << std::fixed << std::setprecision(4)
<< matrix[i * cols + j] << " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
// NVIDIA CUDA Rust: cuda-core manages contexts/streams/buffers with Result error propagation
// while cuda-bindings exposes typed FFI to cuBLAS, cuFFT, cuRAND, cuSPARSE, and cuSOLVER.
use cuda_bindings::{cublas, cufft, curand, cusolver, cusparse, runtime};
use cuda_core::{CudaContext, CudaStream, DeviceBuffer, LaunchConfig};
use std::error::Error;
// Rust's `?` operator replaces C++ CHECK_CUDA_ERROR macros with typed Result propagation
type CudaResult<T = ()> = Result<T, Box<dyn Error>>;
fn print_matrix(matrix: &[f32], rows: usize, cols: usize, name: &str) {
println!("Matrix {name} ({rows}x{cols}):");
for i in 0..rows {
for j in 0..cols {
print!("{:>10.4} ", matrix[i * cols + j]);
}
println!();
}
println!();
}
cuBLAS for Dense Linear Algebra¶
- Reach for cuBLAS whenever you need dense matrix multiplications (GEMM), matrix-vector products, or vector operations. Every deep learning framework routes linear layers and batched projections through cuBLAS or cuBLASLt under the hood.
- The classic cuBLAS column-major trick saves you from ever transposing C/C++ row-major arrays. Because cuBLAS follows Fortran's column-major convention, a row-major matrix \(A\) in memory looks identical to \(A^\top\) in column-major order. Using the algebraic identity \((AB)^\top = B^\top A^\top\), you pass
d_Bas the first operand andd_Aas the second operand tocublasSgemm, which writes \(B^\top A^\top\) in column-major order and therefore produces the exact row-major layout of \(C = AB\) for free.
// Demo 1: cuBLAS for matrix multiplication
void cublasDemoMatrixMultiply() {
std::cout << "\n===== cuBLAS Demo: Matrix Multiplication =====" << std::endl;
// Initialize matrices
const int m = 4, n = 4, k = 4; // Matrix dimensions
float *h_A = new float[m * k]; // m x k matrix
float *h_B = new float[k * n]; // k x n matrix
float *h_C = new float[m * n]; // m x n matrix
// Initialize input matrices
for (int i = 0; i < m * k; i++) h_A[i] = static_cast<float>(i + 1);
for (int i = 0; i < k * n; i++) h_B[i] = static_cast<float>(i + 1);
// Allocate device memory
float *d_A, *d_B, *d_C;
CHECK_CUDA_ERROR(cudaMalloc(&d_A, m * k * sizeof(float)));
CHECK_CUDA_ERROR(cudaMalloc(&d_B, k * n * sizeof(float)));
CHECK_CUDA_ERROR(cudaMalloc(&d_C, m * n * sizeof(float)));
// Copy data to device
CHECK_CUDA_ERROR(cudaMemcpy(d_A, h_A, m * k * sizeof(float), cudaMemcpyHostToDevice));
CHECK_CUDA_ERROR(cudaMemcpy(d_B, h_B, k * n * sizeof(float), cudaMemcpyHostToDevice));
// Create cuBLAS handle
cublasHandle_t handle;
cublasCreate(&handle);
// Perform matrix multiplication: C = A * B
// Note: cuBLAS uses column-major order, but we're using row-major,
// so we compute B * A instead of A * B to get the correct result
const float alpha = 1.0f;
const float beta = 0.0f;
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N,
n, m, k,
&alpha,
d_B, n, // B is treated as the first matrix
d_A, k, // A is treated as the second matrix
&beta,
d_C, n); // Result in C
// Copy result back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_C, d_C, m * n * sizeof(float), cudaMemcpyDeviceToHost));
// Print results
printMatrix(h_A, m, k, "A");
printMatrix(h_B, k, n, "B");
printMatrix(h_C, m, n, "C = A * B");
// Clean up
cublasDestroy(handle);
cudaFree(d_A);
cudaFree(d_B);
cudaFree(d_C);
delete[] h_A;
delete[] h_B;
delete[] h_C;
}
// Demo 1: cuBLAS matrix multiplication via cuda-core + cuda-bindings
// (For custom fused GEMMs in pure Rust, use cutile-rs `mma` tiles.)
fn cublas_demo_matrix_multiply(stream: &CudaStream) -> CudaResult {
println!("
===== cuBLAS Demo: Matrix Multiplication =====");
let (m, n, k) = (4usize, 4usize, 4usize);
let h_a: Vec<f32> = (1..=(m * k)).map(|v| v as f32).collect();
let h_b: Vec<f32> = (1..=(k * n)).map(|v| v as f32).collect();
let d_a = DeviceBuffer::from_host(stream, &h_a)?;
let d_b = DeviceBuffer::from_host(stream, &h_b)?;
let mut d_c = DeviceBuffer::<f32>::zeroed(stream, m * n)?;
unsafe {
let mut handle = std::ptr::null_mut();
cublas::cublasCreate_v2(&mut handle);
// Column-major trick: compute B * A in column-major to obtain row-major C = A * B
let alpha = 1.0f32;
let beta = 0.0f32;
cublas::cublasSgemm_v2(
handle,
cublas::cublasOperation_t::CUBLAS_OP_N,
cublas::cublasOperation_t::CUBLAS_OP_N,
n as i32,
m as i32,
k as i32,
&alpha,
d_b.as_device_ptr() as *const f32,
n as i32,
d_a.as_device_ptr() as *const f32,
k as i32,
&beta,
d_c.as_mut_device_ptr() as *mut f32,
n as i32,
);
cublas::cublasDestroy_v2(handle);
}
let h_c = d_c.to_host_vec(stream)?;
print_matrix(&h_a, m, k, "A");
print_matrix(&h_b, k, n, "B");
print_matrix(&h_c, m, n, "C = A * B");
Ok(())
}
cuFFT for Fast Fourier Transforms¶
- Reach for cuFFT for spectral analysis, audio processing, PDE solvers, and large-kernel FFT convolutions. You create a reusable transform plan (
cufftPlan1d) describing the signal length and complex-to-complex type (CUFFT_C2C), then runcufftExecC2Cin theCUFFT_FORWARDorCUFFT_INVERSEdirection. - Here the input is a sum of two sine waves at frequencies 2 and 4, so the forward spectrum shows sharp magnitude spikes at those bins (and their conjugate mirrors). One crucial gotcha is that cuFFT leaves the inverse transform unnormalised, so you must divide every recovered sample by
signal_sizeto reconstruct the original waveform.
// Demo 2: cuFFT for Fast Fourier Transform
void cufftDemoFFT() {
std::cout << "\n===== cuFFT Demo: 1D Fast Fourier Transform =====" << std::endl;
// Define signal parameters
const int signal_size = 16;
cufftComplex *h_signal = new cufftComplex[signal_size];
cufftComplex *h_result = new cufftComplex[signal_size];
// Create a simple sinusoidal signal
for (int i = 0; i < signal_size; i++) {
float x = static_cast<float>(i) / signal_size;
h_signal[i].x = sin(2 * M_PI * 2 * x) + 0.5f * sin(2 * M_PI * 4 * x); // Real part
h_signal[i].y = 0.0f; // Imaginary part (zero for real signal)
}
// Print original signal
std::cout << "Original signal:" << std::endl;
for (int i = 0; i < signal_size; i++) {
std::cout << std::setw(10) << std::fixed << std::setprecision(4)
<< h_signal[i].x << " + " << h_signal[i].y << "i" << std::endl;
}
// Allocate device memory
cufftComplex *d_signal, *d_result;
CHECK_CUDA_ERROR(cudaMalloc(&d_signal, signal_size * sizeof(cufftComplex)));
CHECK_CUDA_ERROR(cudaMalloc(&d_result, signal_size * sizeof(cufftComplex)));
// Copy data to device
CHECK_CUDA_ERROR(cudaMemcpy(d_signal, h_signal, signal_size * sizeof(cufftComplex), cudaMemcpyHostToDevice));
// Create cuFFT plan
cufftHandle plan;
cufftPlan1d(&plan, signal_size, CUFFT_C2C, 1);
// Execute FFT
cufftExecC2C(plan, d_signal, d_result, CUFFT_FORWARD);
// Copy result back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_result, d_result, signal_size * sizeof(cufftComplex), cudaMemcpyDeviceToHost));
// Print FFT result
std::cout << "\nFFT result:" << std::endl;
for (int i = 0; i < signal_size; i++) {
float magnitude = sqrt(h_result[i].x * h_result[i].x + h_result[i].y * h_result[i].y);
std::cout << "Frequency " << i << ": Magnitude = " << magnitude
<< " (Real: " << h_result[i].x << ", Imag: " << h_result[i].y << ")" << std::endl;
}
// Execute inverse FFT to verify
cufftExecC2C(plan, d_result, d_signal, CUFFT_INVERSE);
// Copy result back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_signal, d_signal, signal_size * sizeof(cufftComplex), cudaMemcpyDeviceToHost));
// Normalize (cuFFT doesn't normalize)
for (int i = 0; i < signal_size; i++) {
h_signal[i].x /= signal_size;
h_signal[i].y /= signal_size;
}
// Print inverse FFT result
std::cout << "\nInverse FFT result (should match original signal):" << std::endl;
for (int i = 0; i < signal_size; i++) {
std::cout << std::setw(10) << std::fixed << std::setprecision(4)
<< h_signal[i].x << " + " << h_signal[i].y << "i" << std::endl;
}
// Clean up
cufftDestroy(plan);
cudaFree(d_signal);
cudaFree(d_result);
delete[] h_signal;
delete[] h_result;
}
// Demo 2: cuFFT 1D Fast Fourier Transform via cuda-core + cuda-bindings
fn cufft_demo_fft(stream: &CudaStream) -> CudaResult {
println!("
===== cuFFT Demo: 1D Fast Fourier Transform =====");
let signal_size = 16usize;
let mut h_signal: Vec<cufft::cufftComplex> = (0..signal_size)
.map(|i| {
let x = i as f32 / signal_size as f32;
let re = (2.0 * std::f32::consts::PI * 2.0 * x).sin()
+ 0.5 * (2.0 * std::f32::consts::PI * 4.0 * x).sin();
cufft::cufftComplex { x: re, y: 0.0 }
})
.collect();
println!("Original signal:");
for c in &h_signal {
println!("{:>10.4} + {:>10.4}i", c.x, c.y);
}
let mut d_signal = DeviceBuffer::from_host(stream, &h_signal)?;
let mut d_result = DeviceBuffer::<cufft::cufftComplex>::zeroed(stream, signal_size)?;
unsafe {
let mut plan: cufft::cufftHandle = 0;
cufft::cufftPlan1d(&mut plan, signal_size as i32, cufft::cufftType::CUFFT_C2C, 1);
// Forward FFT
cufft::cufftExecC2C(
plan,
d_signal.as_mut_device_ptr() as *mut cufft::cufftComplex,
d_result.as_mut_device_ptr() as *mut cufft::cufftComplex,
cufft::CUFFT_FORWARD,
);
let h_result = d_result.to_host_vec(stream)?;
println!("
FFT result:");
for (i, c) in h_result.iter().enumerate() {
let mag = (c.x * c.x + c.y * c.y).sqrt();
println!("Frequency {i}: Magnitude = {mag:.4} (Real: {:.4}, Imag: {:.4})", c.x, c.y);
}
// Inverse FFT (unnormalised — divide by signal_size on host)
cufft::cufftExecC2C(
plan,
d_result.as_mut_device_ptr() as *mut cufft::cufftComplex,
d_signal.as_mut_device_ptr() as *mut cufft::cufftComplex,
cufft::CUFFT_INVERSE,
);
cufft::cufftDestroy(plan);
}
h_signal = d_signal.to_host_vec(stream)?;
for c in &mut h_signal {
c.x /= signal_size as f32;
c.y /= signal_size as f32;
}
println!("
Inverse FFT result (should match original signal):");
for c in &h_signal {
println!("{:>10.4} + {:>10.4}i", c.x, c.y);
}
Ok(())
}
cuRAND for GPU Random Number Generation¶
- Reach for cuRAND whenever you need Monte Carlo simulations, weight initialisation, dropout masks, or diffusion noise at scale. Unlike Tutorial 19 (which used the device-side
curand_kernel.hAPI inside a custom kernel), this demo uses the host-sidecurand.hAPI to fill an entire device buffer in one library call. - After creating a generator with
curandCreateGeneratorand setting a reproducible seed viacurandSetPseudoRandomGeneratorSeed, you can draw both uniform samples in \((0, 1]\) (curandGenerateUniform) and Gaussian samples with specified mean and standard deviation (curandGenerateNormal).
// Demo 3: cuRAND for random number generation
void curandDemoRandomNumbers() {
std::cout << "\n===== cuRAND Demo: Random Number Generation =====" << std::endl;
const int num_samples = 10;
float *h_random = new float[num_samples];
// Allocate device memory
float *d_random;
CHECK_CUDA_ERROR(cudaMalloc(&d_random, num_samples * sizeof(float)));
// Create cuRAND generator
curandGenerator_t generator;
curandCreateGenerator(&generator, CURAND_RNG_PSEUDO_DEFAULT);
// Set seed
curandSetPseudoRandomGeneratorSeed(generator, 1234ULL);
// Generate random numbers (uniform distribution between 0 and 1)
curandGenerateUniform(generator, d_random, num_samples);
// Copy data back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_random, d_random, num_samples * sizeof(float), cudaMemcpyDeviceToHost));
// Print results
std::cout << "Uniform random numbers [0, 1]:" << std::endl;
for (int i = 0; i < num_samples; i++) {
std::cout << std::setw(10) << std::fixed << std::setprecision(6) << h_random[i] << std::endl;
}
// Generate normally distributed random numbers
curandGenerateNormal(generator, d_random, num_samples, 0.0f, 1.0f);
// Copy data back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_random, d_random, num_samples * sizeof(float), cudaMemcpyDeviceToHost));
// Print results
std::cout << "\nNormally distributed random numbers (mean=0, stddev=1):" << std::endl;
for (int i = 0; i < num_samples; i++) {
std::cout << std::setw(10) << std::fixed << std::setprecision(6) << h_random[i] << std::endl;
}
// Clean up
curandDestroyGenerator(generator);
cudaFree(d_random);
delete[] h_random;
}
// Demo 3: cuRAND host-API random number generation via cuda-core + cuda-bindings
fn curand_demo_random_numbers(stream: &CudaStream) -> CudaResult {
println!("
===== cuRAND Demo: Random Number Generation =====");
let num_samples = 10usize;
let mut d_random = DeviceBuffer::<f32>::zeroed(stream, num_samples)?;
unsafe {
let mut generator = std::ptr::null_mut();
curand::curandCreateGenerator(&mut generator, curand::curandRngType::CURAND_RNG_PSEUDO_DEFAULT);
curand::curandSetPseudoRandomGeneratorSeed(generator, 1234);
// Uniform distribution in (0, 1]
curand::curandGenerateUniform(generator, d_random.as_mut_device_ptr() as *mut f32, num_samples);
let h_uniform = d_random.to_host_vec(stream)?;
println!("Uniform random numbers [0, 1]:");
for v in &h_uniform {
println!("{v:>10.6}");
}
// Normal distribution (mean = 0, stddev = 1)
curand::curandGenerateNormal(
generator,
d_random.as_mut_device_ptr() as *mut f32,
num_samples,
0.0,
1.0,
);
let h_normal = d_random.to_host_vec(stream)?;
println!("
Normally distributed random numbers (mean=0, stddev=1):");
for v in &h_normal {
println!("{v:>10.6}");
}
curand::curandDestroyGenerator(generator);
}
Ok(())
}
cuSPARSE for Sparse Matrix Operations¶
- Reach for cuSPARSE when working with graph neural networks, recommender systems, pruned networks, or scientific meshes where almost all matrix entries are zero. Storing only non-zero entries in formats such as Coordinate (COO) or Compressed Sparse Row (CSR) saves enormous memory and skips multiplying by zeros.
- Modern cuSPARSE follows a clean descriptor-plus-workspace pattern. You wrap your row indices, column indices, and non-zero values in a
cusparseSpMatDescr_t(cusparseCreateCoo), wrap dense vectors incusparseDnVecDescr_t, query the required scratch workspace withcusparseSpMV_bufferSize, allocatedBuffer, and runcusparseSpMVto compute \(y = \alpha A x + \beta y\). Note that when adapting this snippet for strict error-checking in production, callcusparseCooSetStridedBatchonly aftercusparseCreateCoohas initialisedmatA.
// Demo 4: cuSPARSE for sparse matrix operations
void cusparseDemoSparseMatrix() {
std::cout << "\n===== cuSPARSE Demo: Sparse Matrix-Vector Multiplication =====" << std::endl;
// Create a sparse matrix in COO format (coordinate format)
// Example 5x5 sparse matrix:
/*
10 0 0 0 0
0 20 0 0 0
0 0 30 0 0
0 0 0 40 0
0 0 0 0 50
*/
const int num_rows = 5;
const int num_cols = 5;
const int num_non_zeros = 5; // Only diagonal elements are non-zero
// COO format components
int *h_row_indices = new int[num_non_zeros]{0, 1, 2, 3, 4}; // Row indices
int *h_col_indices = new int[num_non_zeros]{0, 1, 2, 3, 4}; // Column indices
float *h_values = new float[num_non_zeros]{10.0f, 20.0f, 30.0f, 40.0f, 50.0f}; // Values
// Dense vector x
float *h_x = new float[num_cols]{1.0f, 2.0f, 3.0f, 4.0f, 5.0f};
// Result vector y
float *h_y = new float[num_rows]{0.0f};
// Allocate device memory
int *d_row_indices, *d_col_indices;
float *d_values, *d_x, *d_y;
CHECK_CUDA_ERROR(cudaMalloc(&d_row_indices, num_non_zeros * sizeof(int)));
CHECK_CUDA_ERROR(cudaMalloc(&d_col_indices, num_non_zeros * sizeof(int)));
CHECK_CUDA_ERROR(cudaMalloc(&d_values, num_non_zeros * sizeof(float)));
CHECK_CUDA_ERROR(cudaMalloc(&d_x, num_cols * sizeof(float)));
CHECK_CUDA_ERROR(cudaMalloc(&d_y, num_rows * sizeof(float)));
// Copy data to device
CHECK_CUDA_ERROR(cudaMemcpy(d_row_indices, h_row_indices, num_non_zeros * sizeof(int), cudaMemcpyHostToDevice));
CHECK_CUDA_ERROR(cudaMemcpy(d_col_indices, h_col_indices, num_non_zeros * sizeof(int), cudaMemcpyHostToDevice));
CHECK_CUDA_ERROR(cudaMemcpy(d_values, h_values, num_non_zeros * sizeof(float), cudaMemcpyHostToDevice));
CHECK_CUDA_ERROR(cudaMemcpy(d_x, h_x, num_cols * sizeof(float), cudaMemcpyHostToDevice));
CHECK_CUDA_ERROR(cudaMemcpy(d_y, h_y, num_rows * sizeof(float), cudaMemcpyHostToDevice));
// Create cuSPARSE handle
cusparseHandle_t handle;
cusparseCreate(&handle);
// Create matrix descriptor
cusparseMatDescr_t descr;
cusparseCreateMatDescr(&descr);
cusparseSetMatType(descr, CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(descr, CUSPARSE_INDEX_BASE_ZERO);
// Define alpha and beta scalars
float alpha = 1.0f;
float beta = 0.0f;
// Create COO sparse matrix
cusparseSpMatDescr_t matA;
cusparseCooSetStridedBatch(matA, 1);
cusparseCreateCoo(&matA, num_rows, num_cols, num_non_zeros,
d_row_indices, d_col_indices, d_values,
CUSPARSE_INDEX_32I, CUSPARSE_INDEX_BASE_ZERO, CUDA_R_32F);
// Create dense vectors
cusparseDnVecDescr_t vecX, vecY;
cusparseCreateDnVec(&vecX, num_cols, d_x, CUDA_R_32F);
cusparseCreateDnVec(&vecY, num_rows, d_y, CUDA_R_32F);
// Allocate workspace
size_t bufferSize = 0;
void* dBuffer = NULL;
cusparseSpMV_bufferSize(handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha, matA, vecX, &beta, vecY,
CUDA_R_32F, CUSPARSE_SPMV_ALG_DEFAULT,
&bufferSize);
cudaMalloc(&dBuffer, bufferSize);
// Perform sparse matrix-vector multiplication: y = alpha * A * x + beta * y
cusparseSpMV(handle, CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha, matA, vecX, &beta, vecY,
CUDA_R_32F, CUSPARSE_SPMV_ALG_DEFAULT,
dBuffer);
// Copy result back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_y, d_y, num_rows * sizeof(float), cudaMemcpyDeviceToHost));
// Print sparse matrix
std::cout << "Sparse matrix A:" << std::endl;
for (int i = 0; i < num_non_zeros; i++) {
std::cout << "A[" << h_row_indices[i] << "][" << h_col_indices[i] << "] = " << h_values[i] << std::endl;
}
// Print vector x
std::cout << "\nVector x:" << std::endl;
for (int i = 0; i < num_cols; i++) {
std::cout << "x[" << i << "] = " << h_x[i] << std::endl;
}
// Print result vector y = A * x
std::cout << "\nResult vector y = A * x:" << std::endl;
for (int i = 0; i < num_rows; i++) {
std::cout << "y[" << i << "] = " << h_y[i] << std::endl;
}
// Clean up
cusparseDestroyDnVec(vecX);
cusparseDestroyDnVec(vecY);
cusparseDestroySpMat(matA);
cusparseDestroyMatDescr(descr);
cusparseDestroy(handle);
cudaFree(dBuffer);
cudaFree(d_row_indices);
cudaFree(d_col_indices);
cudaFree(d_values);
cudaFree(d_x);
cudaFree(d_y);
delete[] h_row_indices;
delete[] h_col_indices;
delete[] h_values;
delete[] h_x;
delete[] h_y;
}
// Demo 4: cuSPARSE sparse matrix-vector multiplication (COO SpMV) via cuda-core + cuda-bindings
fn cusparse_demo_sparse_matrix(stream: &CudaStream) -> CudaResult {
println!("
===== cuSPARSE Demo: Sparse Matrix-Vector Multiplication =====");
let (num_rows, num_cols, nnz) = (5i64, 5i64, 5i64);
let h_rows = [0i32, 1, 2, 3, 4];
let h_cols = [0i32, 1, 2, 3, 4];
let h_vals = [10.0f32, 20.0, 30.0, 40.0, 50.0];
let h_x = [1.0f32, 2.0, 3.0, 4.0, 5.0];
let d_rows = DeviceBuffer::from_host(stream, &h_rows)?;
let d_cols = DeviceBuffer::from_host(stream, &h_cols)?;
let d_vals = DeviceBuffer::from_host(stream, &h_vals)?;
let d_x = DeviceBuffer::from_host(stream, &h_x)?;
let mut d_y = DeviceBuffer::<f32>::zeroed(stream, num_rows as usize)?;
unsafe {
let mut handle = std::ptr::null_mut();
cusparse::cusparseCreate(&mut handle);
let (mut mat_a, mut vec_x, mut vec_y) = (std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut());
cusparse::cusparseCreateCoo(
&mut mat_a,
num_rows,
num_cols,
nnz,
d_rows.as_device_ptr() as *mut _,
d_cols.as_device_ptr() as *mut _,
d_vals.as_device_ptr() as *mut _,
cusparse::cusparseIndexType_t::CUSPARSE_INDEX_32I,
cusparse::cusparseIndexBase_t::CUSPARSE_INDEX_BASE_ZERO,
runtime::cudaDataType::CUDA_R_32F,
);
cusparse::cusparseCreateDnVec(&mut vec_x, num_cols, d_x.as_device_ptr() as *mut _, runtime::cudaDataType::CUDA_R_32F);
cusparse::cusparseCreateDnVec(&mut vec_y, num_rows, d_y.as_mut_device_ptr() as *mut _, runtime::cudaDataType::CUDA_R_32F);
let (alpha, beta) = (1.0f32, 0.0f32);
let mut buf_size = 0usize;
cusparse::cusparseSpMV_bufferSize(
handle,
cusparse::cusparseOperation_t::CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha as *const f32 as *const _,
mat_a,
vec_x,
&beta as *const f32 as *const _,
vec_y,
runtime::cudaDataType::CUDA_R_32F,
cusparse::cusparseSpMVAlg_t::CUSPARSE_SPMV_ALG_DEFAULT,
&mut buf_size,
);
let mut d_buf = DeviceBuffer::<u8>::zeroed(stream, buf_size.max(1))?;
cusparse::cusparseSpMV(
handle,
cusparse::cusparseOperation_t::CUSPARSE_OPERATION_NON_TRANSPOSE,
&alpha as *const f32 as *const _,
mat_a,
vec_x,
&beta as *const f32 as *const _,
vec_y,
runtime::cudaDataType::CUDA_R_32F,
cusparse::cusparseSpMVAlg_t::CUSPARSE_SPMV_ALG_DEFAULT,
d_buf.as_mut_device_ptr() as *mut _,
);
cusparse::cusparseDestroyDnVec(vec_x);
cusparse::cusparseDestroyDnVec(vec_y);
cusparse::cusparseDestroySpMat(mat_a);
cusparse::cusparseDestroy(handle);
}
let h_y = d_y.to_host_vec(stream)?;
println!("Result vector y = A * x:");
for (i, &val) in h_y.iter().enumerate() {
println!("y[{i}] = {val}");
}
Ok(())
}
cuSOLVER for Direct Linear Solvers¶
- Reach for cuSOLVER when solving dense or sparse linear systems \(Ax = b\), least-squares regressions, QR/Cholesky decompositions, singular value decompositions (SVD), or eigenproblems on the GPU.
- Just like cuBLAS, cuSOLVER expects matrices in column-major order, so
h_Ais stored column by column. The demo computes an in-place LU factorisation with partial pivoting viacusolverDnSgetrf, checksd_infoto confirm the matrix is non-singular, solves for \(x\) in place insided_bviacusolverDnSgetrs, and verifies \(Ax = b\) back on the host.
// Demo 5: cuSOLVER for solving linear systems
void cusolverDemoLinearSolve() {
std::cout << "\n===== cuSOLVER Demo: Solving Linear System Ax = b =====" << std::endl;
// Define a linear system Ax = b
/*
3x + 1y - 2z = 5
2x + 6y + 4z = 31
1x + 1y + 8z = 17
*/
const int n = 3; // System size (3x3)
// Matrix A (column-major for cuSOLVER)
float h_A[n * n] = {
3.0f, 2.0f, 1.0f, // First column
1.0f, 6.0f, 1.0f, // Second column
-2.0f, 4.0f, 8.0f // Third column
};
// Right-hand side b
float h_b[n] = {5.0f, 31.0f, 17.0f};
// Solution vector x
float h_x[n];
// Allocate device memory
float *d_A, *d_b, *d_work;
int *d_info, h_info = 0;
CHECK_CUDA_ERROR(cudaMalloc(&d_A, n * n * sizeof(float)));
CHECK_CUDA_ERROR(cudaMalloc(&d_b, n * sizeof(float)));
CHECK_CUDA_ERROR(cudaMalloc(&d_info, sizeof(int)));
// Copy data to device
CHECK_CUDA_ERROR(cudaMemcpy(d_A, h_A, n * n * sizeof(float), cudaMemcpyHostToDevice));
CHECK_CUDA_ERROR(cudaMemcpy(d_b, h_b, n * sizeof(float), cudaMemcpyHostToDevice));
// Create cuSOLVER handle
cusolverDnHandle_t handle;
cusolverDnCreate(&handle);
// Calculate workspace size
int workspace_size = 0;
cusolverDnSgetrf_bufferSize(handle, n, n, d_A, n, &workspace_size);
// Allocate workspace
CHECK_CUDA_ERROR(cudaMalloc(&d_work, workspace_size * sizeof(float)));
// LU factorization
int *d_pivot;
CHECK_CUDA_ERROR(cudaMalloc(&d_pivot, n * sizeof(int)));
cusolverDnSgetrf(handle, n, n, d_A, n, d_work, d_pivot, d_info);
// Check if factorization was successful
CHECK_CUDA_ERROR(cudaMemcpy(&h_info, d_info, sizeof(int), cudaMemcpyDeviceToHost));
if (h_info != 0) {
std::cerr << "LU factorization failed: " << h_info << std::endl;
} else {
// Solve the linear system
cusolverDnSgetrs(handle, CUBLAS_OP_N, n, 1, d_A, n, d_pivot, d_b, n, d_info);
// Copy solution back to host
CHECK_CUDA_ERROR(cudaMemcpy(h_x, d_b, n * sizeof(float), cudaMemcpyDeviceToHost));
// Print the matrix A
std::cout << "Matrix A:" << std::endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
// Convert from column-major to row-major for printing
std::cout << std::setw(10) << std::fixed << std::setprecision(2)
<< h_A[j * n + i] << " ";
}
std::cout << std::endl;
}
// Print the right-hand side b
std::cout << "\nVector b:" << std::endl;
for (int i = 0; i < n; i++) {
std::cout << std::setw(10) << std::fixed << std::setprecision(2) << h_b[i] << std::endl;
}
// Print the solution x
std::cout << "\nSolution x:" << std::endl;
for (int i = 0; i < n; i++) {
std::cout << "x[" << i << "] = " << std::setw(10) << std::fixed << std::setprecision(6) << h_x[i] << std::endl;
}
// Verify solution by calculating Ax
std::cout << "\nVerifying solution (Ax should equal b):" << std::endl;
for (int i = 0; i < n; i++) {
float sum = 0.0f;
for (int j = 0; j < n; j++) {
// Convert from column-major to row-major for calculation
sum += h_A[j * n + i] * h_x[j];
}
std::cout << "Row " << i << ": " << std::setw(10) << std::fixed << std::setprecision(6)
<< sum << " (should be " << h_b[i] << ")" << std::endl;
}
}
// Clean up
cusolverDnDestroy(handle);
cudaFree(d_A);
cudaFree(d_b);
cudaFree(d_work);
cudaFree(d_info);
cudaFree(d_pivot);
}
// Demo 5: cuSOLVER LU factorisation & linear solve (Ax = b) via cuda-core + cuda-bindings
fn cusolver_demo_linear_solve(stream: &CudaStream) -> CudaResult {
println!("
===== cuSOLVER Demo: Solving Linear System Ax = b =====");
let n = 3usize;
// Column-major matrix A for cuSOLVER
let h_a: [f32; 9] = [
3.0, 2.0, 1.0, // First column
1.0, 6.0, 1.0, // Second column
-2.0, 4.0, 8.0, // Third column
];
let h_b: [f32; 3] = [5.0, 31.0, 17.0];
let mut d_a = DeviceBuffer::from_host(stream, &h_a)?;
let mut d_b = DeviceBuffer::from_host(stream, &h_b)?;
let mut d_pivot = DeviceBuffer::<i32>::zeroed(stream, n)?;
let mut d_info = DeviceBuffer::<i32>::zeroed(stream, 1)?;
unsafe {
let mut handle = std::ptr::null_mut();
cusolver::cusolverDnCreate(&mut handle);
let mut lwork = 0i32;
cusolver::cusolverDnSgetrf_bufferSize(
handle,
n as i32,
n as i32,
d_a.as_mut_device_ptr() as *mut f32,
n as i32,
&mut lwork,
);
let mut d_work = DeviceBuffer::<f32>::zeroed(stream, lwork.max(1) as usize)?;
// In-place LU factorisation with partial pivoting
cusolver::cusolverDnSgetrf(
handle,
n as i32,
n as i32,
d_a.as_mut_device_ptr() as *mut f32,
n as i32,
d_work.as_mut_device_ptr() as *mut f32,
d_pivot.as_mut_device_ptr() as *mut i32,
d_info.as_mut_device_ptr() as *mut i32,
);
let info = d_info.to_host_vec(stream)?[0];
if info != 0 {
eprintln!("LU factorization failed: {info}");
} else {
cusolver::cusolverDnSgetrs(
handle,
cublas::cublasOperation_t::CUBLAS_OP_N,
n as i32,
1,
d_a.as_device_ptr() as *const f32,
n as i32,
d_pivot.as_device_ptr() as *const i32,
d_b.as_mut_device_ptr() as *mut f32,
n as i32,
d_info.as_mut_device_ptr() as *mut i32,
);
let h_x = d_b.to_host_vec(stream)?;
println!("Solution x:");
for (i, &val) in h_x.iter().enumerate() {
println!("x[{i}] = {val:>10.6}");
}
println!("
Verifying solution (Ax should equal b):");
for i in 0..n {
let sum: f32 = (0..n).map(|j| h_a[j * n + i] * h_x[j]).sum();
println!("Row {i}: {sum:>10.6} (should be {:.2})", h_b[i]);
}
}
cusolver::cusolverDnDestroy(handle);
}
Ok(())
}
Thrust for High-Level Parallel Algorithms¶
- Reach for Thrust when you want C++ Standard Library ergonomics on the GPU without writing boilerplate
cudaMalloc,cudaMemcpy, or reduction kernels. - Constructing a
thrust::device_vector<float>from astd::vector<float>automatically allocates GPU memory and copies data over, freeing it when the vector leaves scope. From there,thrust::sort,thrust::reduce(withplus,minimum, andmaximumfunctors), andthrust::transform(withsquare) dispatch highly optimised parallel primitives in a single line each.
// Demo 6: Thrust for parallel algorithms
void thrustDemoParallelAlgorithms() {
std::cout << "\n===== Thrust Demo: Parallel Algorithms =====" << std::endl;
const int size = 10;
// Generate data on host
std::vector<float> h_data(size);
for (int i = 0; i < size; i++) {
h_data[i] = static_cast<float>(rand() % 100);
}
// Print original data
std::cout << "Original data:" << std::endl;
for (int i = 0; i < size; i++) {
std::cout << h_data[i] << " ";
}
std::cout << std::endl;
// Transfer data to device
thrust::device_vector<float> d_data(h_data.begin(), h_data.end());
// Sort data
thrust::sort(d_data.begin(), d_data.end());
// Transfer sorted data back to host
thrust::copy(d_data.begin(), d_data.end(), h_data.begin());
// Print sorted data
std::cout << "\nSorted data:" << std::endl;
for (int i = 0; i < size; i++) {
std::cout << h_data[i] << " ";
}
std::cout << std::endl;
// Find sum using reduction
float sum = thrust::reduce(d_data.begin(), d_data.end(), 0.0f, thrust::plus<float>());
// Find minimum and maximum values
float min_val = thrust::reduce(d_data.begin(), d_data.end(), FLT_MAX, thrust::minimum<float>());
float max_val = thrust::reduce(d_data.begin(), d_data.end(), -FLT_MAX, thrust::maximum<float>());
// Print reduction results
std::cout << "\nReduction results:" << std::endl;
std::cout << "Sum: " << sum << std::endl;
std::cout << "Min: " << min_val << std::endl;
std::cout << "Max: " << max_val << std::endl;
std::cout << "Average: " << sum / size << std::endl;
// Create a new vector with transformed values (square each value)
thrust::device_vector<float> d_squared(size);
thrust::transform(d_data.begin(), d_data.end(), d_squared.begin(), thrust::square<float>());
// Transfer squared data back to host
std::vector<float> h_squared(size);
thrust::copy(d_squared.begin(), d_squared.end(), h_squared.begin());
// Print squared data
std::cout << "\nSquared data:" << std::endl;
for (int i = 0; i < size; i++) {
std::cout << h_squared[i] << " ";
}
std::cout << std::endl;
}
// Demo 6: High-level parallel transform & reduction in CUDA Rust (cuda-oxide)
use cuda_device::atomic::{AtomicOrdering, DeviceAtomicF32};
use cuda_device::{DisjointSlice, SharedArray, cuda_module, kernel, thread, warp};
#[cuda_module]
mod parallel_ops {
use super::*;
#[kernel]
pub fn square_transform(input: &[f32], mut output: DisjointSlice<f32>) {
let idx = thread::index_1d();
let i = idx.get();
if let Some(out) = output.get_mut(idx) {
*out = input[i] * input[i];
}
}
#[kernel]
pub fn block_reduce_sum(data: &[f32], out: &[DeviceAtomicF32]) {
static mut SMEM: SharedArray<f32, 32> = SharedArray::UNINIT;
let tid = thread::threadIdx_x() as usize;
let gid = thread::index_1d().get();
let val = if gid < data.len() { data[gid] } else { 0.0 };
let wsum = warp::reduce_sum_f32(val);
if tid % 32 == 0 {
unsafe { SMEM[tid / 32] = wsum };
}
thread::sync_threads();
if tid == 0 {
let warps = (thread::blockDim_x() as usize).div_ceil(32);
let mut total = 0.0f32;
for w in 0..warps {
total += unsafe { SMEM[w] };
}
out[0].fetch_add(total, AtomicOrdering::Relaxed);
}
}
}
fn rust_gpu_parallel_algorithms(ctx: &CudaContext, stream: &CudaStream) -> CudaResult {
println!("
===== CUDA Rust Demo: Parallel Algorithms =====");
let mut h_data: Vec<f32> = vec![42.0, 7.0, 91.0, 15.0, 63.0, 28.0, 4.0, 80.0, 51.0, 19.0];
println!("Original data: {h_data:?}");
h_data.sort_by(f32::total_cmp);
println!("Sorted data: {h_data:?}");
let d_data = DeviceBuffer::from_host(stream, &h_data)?;
let d_sum = DeviceBuffer::<f32>::zeroed(stream, 1)?;
let mut d_squared = DeviceBuffer::<f32>::zeroed(stream, h_data.len())?;
let module = parallel_ops::load(ctx)?;
let cfg = LaunchConfig::for_num_elems(h_data.len() as u32);
unsafe {
module.block_reduce_sum(stream, cfg, &d_data, &d_sum)?;
module.square_transform(stream, cfg, &d_data, &mut d_squared)?;
}
let sum = d_sum.to_host_vec(stream)?[0];
let min_val = h_data.first().copied().unwrap_or(0.0);
let max_val = h_data.last().copied().unwrap_or(0.0);
let h_squared = d_squared.to_host_vec(stream)?;
println!("Sum: {sum}, Min: {min_val}, Max: {max_val}, Average: {}", sum / h_data.len() as f32);
println!("Squared data: {h_squared:?}");
Ok(())
}
Running All Six Library Demos¶
- Finally,
main()queries every installed CUDA device withcudaGetDeviceCountandcudaGetDeviceProperties(printing compute capability, VRAM, streaming multiprocessor count, and thread-block limits) before executing all six demos in order.
int main() {
// Show available CUDA devices
int deviceCount = 0;
cudaGetDeviceCount(&deviceCount);
std::cout << "CUDA Libraries Demo" << std::endl;
std::cout << "===================" << std::endl;
std::cout << "Found " << deviceCount << " CUDA-capable device(s)" << std::endl;
// Print device properties
for (int i = 0; i < deviceCount; i++) {
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, i);
std::cout << "\nDevice " << i << ": " << deviceProp.name << std::endl;
std::cout << " Compute Capability: " << deviceProp.major << "." << deviceProp.minor << std::endl;
std::cout << " Total Global Memory: " << deviceProp.totalGlobalMem / (1024 * 1024) << " MB" << std::endl;
std::cout << " Multiprocessors: " << deviceProp.multiProcessorCount << std::endl;
std::cout << " Max Threads per Block: " << deviceProp.maxThreadsPerBlock << std::endl;
}
std::cout << std::endl;
// Run library demos
cublasDemoMatrixMultiply();
cufftDemoFFT();
curandDemoRandomNumbers();
cusparseDemoSparseMatrix();
cusolverDemoLinearSolve();
thrustDemoParallelAlgorithms();
std::cout << "\nAll demos completed successfully!" << std::endl;
return 0;
}
fn main() -> CudaResult {
let device_count = cuda_core::device_count()?;
println!("CUDA Rust Libraries Demo");
println!("========================");
println!("Found {device_count} CUDA-capable device(s)");
for i in 0..device_count {
let mut prop = unsafe { std::mem::zeroed::<runtime::cudaDeviceProp>() };
unsafe { runtime::cudaGetDeviceProperties(&mut prop, i) };
let name = unsafe { std::ffi::CStr::from_ptr(prop.name.as_ptr()) }.to_string_lossy();
println!("
Device {i}: {name}");
println!(" Compute Capability: {}.{}", prop.major, prop.minor);
println!(" Total Global Memory: {} MB", prop.totalGlobalMem / (1024 * 1024));
println!(" Multiprocessors: {}", prop.multiProcessorCount);
println!(" Max Threads per Block: {}", prop.maxThreadsPerBlock);
}
let ctx = CudaContext::new(0)?;
let stream = ctx.default_stream();
cublas_demo_matrix_multiply(&stream)?;
cufft_demo_fft(&stream)?;
curand_demo_random_numbers(&stream)?;
cusparse_demo_sparse_matrix(&stream)?;
cusolver_demo_linear_solve(&stream)?;
rust_gpu_parallel_algorithms(&ctx, &stream)?;
println!("
All demos completed successfully!");
Ok(())
}
Take-Home¶
- Fuse memory-bound chains into one kernel. Operations like attention spend most of their time shuttling intermediate tensors to and from HBM, so keeping exponentials and sums in shared memory and registers delivers dramatic speedups.
- Tile overlapping neighbourhoods with halo borders. Whenever adjacent threads read overlapping windows (as in 2D convolution or stencil codes), loading a shared-memory tile plus its halo turns repeated global reads into fast on-chip reuses.
- Move the environment loop onto the GPU for RL. Parallelising action selection, physics or grid stepping, and Q-value updates across hundreds of GPU threads with per-thread
curandStategenerators removes the CPU-GPU bottleneck from rollout collection. - Reach for NVIDIA's libraries before hand-rolling standard maths. Use cuBLAS for dense GEMMs (remembering the row-major \(B^\top A^\top\) trick), cuFFT for spectral transforms (remembering to normalise the inverse), cuRAND for batched sampling, cuSPARSE for sparse linear algebra, cuSOLVER for direct decompositions, and Thrust for STL-style sorts, scans, and reductions.
- Measure kernels with CUDA events and check every error code. Wrapping API calls in
CHECK_CUDA_ERRORand timing withcudaEventRecordkeeps asynchronous GPU bugs and measurement mistakes from slipping past unnoticed.