how to write a CUDA kernel for vector addition, for a beginner
- User
how to write a CUDA kernel for vector addition, for a beginner
- Assistant
how to write a CUDA kernel for vector addition, for a beginner
Sure! Writing a CUDA kernel for vector addition is a great way to get started with GPU programming. I'll guide you through the process step by step, assuming you're new to CUDA and parallel programming.
CUDA (Compute Unified Device Architecture) is a parallel computing platform and programming model developed by NVIDIA. It enables software developers to use a CUDA-enabled graphics processing unit (GPU) for general purpose processing. CUDA provides extensions to the C and C++ languages, making it easy to write programs that run on the GPU.
Vector addition involves adding two arrays (vectors) element-wise. Given two arrays A and B, the result C is computed as:
[ C[i] = A[i] + B[i] ]
This operation is ideal for parallel execution because each addition can be performed independently.
Before we begin, make sure you have:
A CUDA kernel is a function that runs on the GPU. Here's how you can write a simple vector addition kernel:
// Vector addition kernel
__global__ void vectorAdd(const float *A, const float *B, float *C, int numElements)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < numElements)
{
C[i] = A[i] + B[i];
}
}
Explanation:
__global__ indicates that this function is a GPU kernel.blockDim, blockIdx, and threadIdx are built-in variables provided by CUDA to identify each thread's unique index.int i = blockDim.x * blockIdx.x + threadIdx.x; computes a global thread index.if condition ensures we don't access out-of-bounds memory.The host code runs on the CPU and is responsible for:
Here's how you can write the host code:
Explanation:
cuda_runtime.h is needed for CUDA runtime API, and stdio.h for input/output operations.cudaError_t type and cudaGetErrorString to check and report errors.malloc.cudaMalloc.h_A and h_B are initialized with random values.cudaMemcpy.<<<...>>> syntax.cudaFree and host memory with free.Save your code in a file named vector_add.cu.
Use the NVIDIA CUDA Compiler nvcc to compile the program:
nvcc vector_add.cu -o vector_add
Execute the compiled program:
./vector_add
When launching a kernel, you specify the execution configuration:
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, numElements);
threadsPerBlock: Number of threads in a block (e.g., 256 threads).
blocksPerGrid: Number of blocks in the grid, calculated as:
[ \text{blocksPerGrid} = \frac{\text{numElements} + \text{threadsPerBlock} - 1}{\text{threadsPerBlock}} ]
This calculation ensures that there are enough threads to cover all elements, even if numElements isn't divisible by threadsPerBlock.
cudaMemcpy. For more complex programs, you may need to use cudaDeviceSynchronize() after kernel launches.threadsPerBlock to see how it affects performance. Common sizes are multiples of 32 due to the GPU's warp size.Here's the full code with both the kernel and the host code:
// vector_add.cu
#include <stdio.h>
#include <cuda_runtime.h>
// CUDA Kernel function for vector addition
__global__ void vectorAdd(const float *A, const float *B, float *C, int numElements)
{
int i = blockDim.x * blockIdx.x + threadIdx.x;
if (i < numElements)
{
C[i] = A[i] + B[i];
}
}
int main(void)
{
// ... [Host code from previous section] ...
}
You've just written a simple CUDA program that performs vector addition on the GPU. This example demonstrates basic CUDA concepts:
Feel free to ask if you have any questions or need further assistance!
Not yet included in a published release.
#include <stdio.h>
#include <cuda_runtime.h>
int main(void)
{
// Error code to check return values
cudaError_t err = cudaSuccess;
// Size of the vector
int numElements = 50000;
size_t size = numElements * sizeof(float);
printf("[Vector addition of %d elements]\n", numElements);
// Allocate host memory
float *h_A = (float *)malloc(size);
float *h_B = (float *)malloc(size);
float *h_C = (float *)malloc(size);
// Verify allocations
if (h_A == NULL || h_B == NULL || h_C == NULL)
{
fprintf(stderr, "Failed to allocate host vectors!\n");
exit(EXIT_FAILURE);
}
// Initialize host vectors
for (int i = 0; i < numElements; ++i)
{
h_A[i] = rand() / (float)RAND_MAX;
h_B[i] = rand() / (float)RAND_MAX;
}
// Allocate device memory
float *d_A = NULL;
err = cudaMalloc((void **)&d_A, size);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device vector A (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
float *d_B = NULL;
err = cudaMalloc((void **)&d_B, size);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device vector B (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
float *d_C = NULL;
err = cudaMalloc((void **)&d_C, size);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to allocate device vector C (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Copy host vectors to device
printf("Copy input data from the host memory to the CUDA device\n");
err = cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice);
// Check for errors
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy vector A from host to device (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy vector B from host to device (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Launch the vector add CUDA Kernel
int threadsPerBlock = 256;
int blocksPerGrid =(numElements + threadsPerBlock - 1) / threadsPerBlock;
printf("CUDA kernel launch with %d blocks of %d threads\n", blocksPerGrid, threadsPerBlock);
vectorAdd<<<blocksPerGrid, threadsPerBlock>>>(d_A, d_B, d_C, numElements);
// Wait for GPU to finish
err = cudaGetLastError();
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to launch vectorAdd kernel (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Copy result back to host
printf("Copy output data from the CUDA device to the host memory\n");
err = cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to copy vector C from device to host (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Verify result
for (int i = 0; i < numElements; ++i)
{
if (fabs(h_A[i] + h_B[i] - h_C[i]) > 1e-5)
{
fprintf(stderr, "Result verification failed at element %d!\n", i);
exit(EXIT_FAILURE);
}
}
printf("Test PASSED\n");
// Free device memory
err = cudaFree(d_A);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device vector A (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_B);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device vector B (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
err = cudaFree(d_C);
if (err != cudaSuccess)
{
fprintf(stderr, "Failed to free device vector C (error code %s)\n", cudaGetErrorString(err));
exit(EXIT_FAILURE);
}
// Free host memory
free(h_A);
free(h_B);
free(h_C);
printf("Done\n");
return 0;
}