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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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);
}
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;
}
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;
}
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.