Vector addition
The "hello world" of CUDA — and a tour of four different ways to get data onto the GPU.
- How a thread works out which element of the array it is responsible for
- Why the grid size formula has that odd "+ NUM_THREADS - 1" in it
- That moving data, not adding numbers, is what actually costs time
Adding two vectors is embarrassingly parallel: element c[i] depends only on a[i] and b[i], so every element could in principle be computed at the same instant. That makes it useless as a benchmark and perfect as a first kernel, because nothing distracts from the two things you must get right — indexing and memory movement.
One thread, one element
A CUDA kernel is written from the point of view of a single thread. The GPU launches thousands of copies of it, and the only thing distinguishing one copy from another is its position in the grid.
__global__ void vectorAdd(int* a, int* b, int* c, int N) {
// Where am I in the whole grid?
int tid = (blockIdx.x * blockDim.x) + threadIdx.x;
// Threads past the end of the array must not write
if (tid < N) {
c[tid] = a[tid] + b[tid];
}
}
Threads are grouped into blocks, and blocks into a grid. threadIdx.x is the thread’s index inside its block, blockIdx.x is the block’s index in the grid, and blockDim.x is how many threads a block holds. Multiply and add, and you get a unique global id for every thread.
The boundary check matters. You almost always launch slightly more threads than there is data, and without if (tid < N) the extras write past the end of the array — which on a GPU is silent corruption, not a crash.
if (tid < N) catches.Sizing the grid
int NUM_THREADS = 1 << 10; // 1024 threads per block
int NUM_BLOCKS = (N + NUM_THREADS - 1) / NUM_THREADS; // round up, don't round down
Integer division truncates, so N / NUM_THREADS would leave the remainder unprocessed — with N = 1025 and 1024 threads per block you would get 1 block and one element silently skipped. Adding NUM_THREADS - 1 before dividing rounds up instead, which is why you see this idiom in nearly every CUDA program.
The part that actually costs time
cudaMalloc(&d_a, bytes);
cudaMemcpy(d_a, a.data(), bytes, cudaMemcpyHostToDevice); // CPU -> GPU
vectorAdd<<<NUM_BLOCKS, NUM_THREADS>>>(d_a, d_b, d_c, N);
cudaMemcpy(c.data(), d_c, bytes, cudaMemcpyDeviceToHost); // GPU -> CPU
The arithmetic here is trivial; the transfers across the PCIe bus are not. That is the whole lesson of this chapter, and it is why the folder contains five versions of the same program:
| Version | Technique | Relative speed |
|---|---|---|
01vec_add_baseline.cu | cudaMalloc + cudaMemcpy | 1× (baseline) |
02vec_add_pinned_memory.cu | page-locked host memory | ~1.5× |
03vec_add_unified_memory_baseline.cu | unified memory, managed automatically | ~1.2× |
04vec_add_unified_memory_prefetch.cu | unified memory + explicit prefetch | ~2× |
05cuBLAS_vec_add.cu | cuBLAS axpy | ~3–4× |
Pinned memory is host memory the OS promises never to swap out, so the GPU can read it directly instead of through a staging buffer. Unified memory gives one pointer valid on both sides and migrates pages on demand — convenient, but it migrates lazily, which is why adding cudaMemPrefetchAsync nearly doubles it again by moving the data before the kernel asks for it.
Note the shape of that table: every speedup comes from changing how memory is handled. None of them changed the addition.
Also worth knowing: kernel launches are asynchronous. The CPU keeps running after vectorAdd<<<...>>>. The cudaMemcpy that follows is synchronous, so it doubles as the synchronisation point — which is why this program needs no explicit cudaDeviceSynchronize().
Run it
cd cuda_from_scratch/01vector_addition
nvcc -o vec_add 01vec_add_baseline.cu
./vec_add
The cuBLAS version needs its library linked:
nvcc -o vec_add_cublas 05cuBLAS_vec_add.cu -lcublas
verify_result asserts every element on the CPU, so Completed Sucessfully means the GPU agreed with the CPU.
Try it yourself. Delete the if (tid < N) guard and change N to something not divisible by 1024, say 1 << 16 plus 1. Does it crash, or does it quietly produce a wrong answer? Then time the baseline against the pinned-memory version with nvprof or nsys profile and check where the time actually goes.