Short answer
CUDA lets you write C++ functions called kernels that run on thousands of GPU threads at once. You mark a function with __global__, launch it with the kernel<<<blocks, threads>>>(args) syntax, and each thread works out which piece of data to process from its block and thread index. This guide walks through a complete vector-add program, explains threads, blocks, grids and warps, and covers the performance ideas that matter most: memory coalescing, shared memory and occupancy, plus when to use libraries like cuBLAS or higher-level tools like Triton instead.
What you need
- An NVIDIA GPU (any recent GeForce, RTX or data center card)
- The CUDA Toolkit from NVIDIA, which includes the
nvcccompiler - A C++ compiler (Visual Studio on Windows, GCC on Linux)
No GPU? Rent one by the hour from a cloud provider; compare prices in our GPU cloud price tracker. For background, see What is CUDA? and How a GPU works.
The CUDA mental model
- Host = the CPU and its memory. Device = the GPU and its memory.
- A kernel is a function that runs on the device, executed by many threads in parallel.
- Threads are grouped into blocks (up to 1,024 threads each), and blocks form a grid.
- Each block runs on one streaming multiprocessor (SM); the hardware executes threads in groups of 32 called warps.
- Every thread knows its position through built-in variables:
threadIdx,blockIdx,blockDimandgridDim.
| Level | Built-in variable | Typical size |
|---|---|---|
| Thread | threadIdx.x | 1 |
| Warp | (implicit) | 32 threads |
| Block | blockIdx.x, blockDim.x | 128–1,024 threads |
| Grid | gridDim.x | Thousands of blocks |
Your first kernel: adding two vectors
Save this as add.cu:
#include <cstdio>
#include <cmath>
#include <cuda_runtime.h>
// Runs on the GPU: each thread adds a subset of elements.
__global__ void add(int n, const float* x, const float* y, float* out) {
int i = blockIdx.x * blockDim.x + threadIdx.x; // global thread index
int stride = blockDim.x * gridDim.x; // total threads in the grid
for (; i < n; i += stride) { // grid-stride loop
out[i] = x[i] + y[i];
}
}
int main() {
const int n = 1 << 24; // 16.7 million elements
float *x, *y, *out;
cudaMallocManaged(&x, n * sizeof(float)); // memory visible to CPU and GPU
cudaMallocManaged(&y, n * sizeof(float));
cudaMallocManaged(&out, n * sizeof(float));
for (int i = 0; i < n; i++) { x[i] = 1.0f; y[i] = 2.0f; }
int threads = 256;
int blocks = (n + threads - 1) / threads;
add<<<blocks, threads>>>(n, x, y, out);
cudaError_t err = cudaDeviceSynchronize(); // wait for the GPU to finish
if (err != cudaSuccess) { printf("CUDA error: %s\n", cudaGetErrorString(err)); return 1; }
float max_error = 0.0f;
for (int i = 0; i < n; i++) max_error = fmaxf(max_error, fabsf(out[i] - 3.0f));
printf("Max error: %f\n", max_error);
cudaFree(x); cudaFree(y); cudaFree(out);
return 0;
}Compile and run:
nvcc -O3 add.cu -o add
./addYou should see Max error: 0.000000.
What just happened
1. cudaMallocManaged allocated unified memory that both CPU and GPU can access; the driver moves data as needed. 2. add<<<blocks, threads>>> launched about 65,536 blocks of 256 threads, one thread per element. 3. Each thread computed its global index from blockIdx, blockDim and threadIdx. 4. The grid-stride loop means the kernel still works if you launch fewer threads than elements. 5. cudaDeviceSynchronize waited for the asynchronous kernel and reported any errors.
Explicit memory copies
Unified memory is convenient, but production code often manages transfers explicitly for predictable performance:
float *d_x;
cudaMalloc(&d_x, n * sizeof(float));
cudaMemcpy(d_x, h_x, n * sizeof(float), cudaMemcpyHostToDevice);
// ... launch kernels using d_x ...
cudaMemcpy(h_x, d_x, n * sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(d_x);Moving data over PCIe is slow compared with GPU memory, so the golden rule is: copy data to the GPU once, do as much work there as possible, and copy results back once.
Measuring performance
Vector add does almost no maths per byte, so it is memory-bound: its speed is limited by memory bandwidth. Measure effective bandwidth with CUDA events:
cudaEvent_t start, stop;
cudaEventCreate(&start); cudaEventCreate(&stop);
cudaEventRecord(start);
add<<<blocks, threads>>>(n, x, y, out);
cudaEventRecord(stop);
cudaEventSynchronize(stop);
float ms = 0; cudaEventElapsedTime(&ms, start, stop);
double gbps = 3.0 * n * sizeof(float) / (ms / 1000.0) / 1e9; // 2 reads + 1 write
printf("%.3f ms, %.1f GB/s\n", ms, gbps);Run the kernel once to warm up (and to move unified memory to the GPU) before timing. A well-written memory-bound kernel reaches a large fraction of the GPU's rated bandwidth. For deeper analysis, use NVIDIA's profilers: Nsight Systems (nsys) for timelines and Nsight Compute (ncu) for kernel-level metrics. The roofline model simulator shows why some kernels are limited by bandwidth and others by compute.
The performance ideas that matter most
1. Memory coalescing
When the 32 threads of a warp access consecutive addresses, the hardware combines them into a few wide memory transactions. Scattered or strided access wastes bandwidth. Our kernel is coalesced because thread i reads element i.
2. Shared memory
Each SM has fast on-chip shared memory that threads in a block can use cooperatively. The classic use is tiling: load a tile of data from slow global memory once, then reuse it many times from shared memory. This is the core idea behind fast matrix multiplication and FlashAttention.
__global__ void tile_example(const float* in, float* out) {
__shared__ float tile[256];
int i = blockIdx.x * blockDim.x + threadIdx.x;
tile[threadIdx.x] = in[i];
__syncthreads(); // wait until the whole tile is loaded
// ... threads can now read neighbours' values cheaply from tile[] ...
out[i] = tile[threadIdx.x];
}3. Occupancy and block size
Each SM can host a limited number of threads, registers and shared memory. Enough active warps let the GPU hide memory latency by switching between them. Block sizes of 128–512 threads (multiples of 32) are good starting points.
4. Avoid warp divergence
If threads in a warp take different branches of an if, the warp executes both paths one after another. Keep branches uniform within warps where possible.
5. Use the right precision and tensor cores
Most AI maths runs on tensor cores in FP16, BF16, FP8 or FP4, which are far faster than regular CUDA cores. Programming them directly (WMMA, MMA instructions, or CUTLASS) is advanced; most developers reach them through libraries. See tensor cores vs CUDA cores and precision formats.
Don't reinvent the wheel: libraries and higher-level tools
| Tool | Use it for |
|---|---|
| cuBLAS / cuBLASLt | Matrix multiplication (GEMM) with tensor cores |
| cuDNN | Neural network layers (convolutions, attention, normalisation) |
| CUTLASS / CuTe | Building custom high-performance GEMM and attention kernels in C++ |
| Thrust / CUB | Sorting, scanning, reductions |
| OpenAI Triton | Writing GPU kernels in Python with automatic tiling and optimisation |
PyTorch (torch.compile) | Fusing operations and generating kernels automatically |
A hand-written naive matrix multiply is typically many times slower than cuBLAS. Write custom kernels when you need to fuse several operations to avoid memory round trips, or for operations no library provides.
A learning path
1. Vector add, then element-wise operations (ReLU, scaling). 2. Reductions (sum, max) using shared memory and warp shuffles. 3. Tiled matrix multiplication; compare with cuBLAS. 4. Softmax and layer norm kernels, the building blocks of transformers. 5. Try the same kernels in Triton and compare effort and speed. 6. Read about FlashAttention and how GPUs work at the hardware level.
Frequently asked questions
Do I need to know C++ to use CUDA?
For CUDA C++, yes, basic C++ is enough to start. Alternatives include Triton and CuPy (Python), Numba (Python), and CUDA Python bindings.
Does CUDA work on AMD GPUs?
Not directly. AMD's ROCm platform offers HIP, a very similar programming model, and tools to convert CUDA code. See AMD vs NVIDIA for AI.
Why is my first kernel slower than the CPU?
Small problems, data transfer time and the first-launch overhead can outweigh GPU speed. GPUs shine on large, parallel workloads with data that stays on the device.
Should AI engineers learn CUDA?
You don't need it to train or use models, but understanding CUDA explains why techniques like FlashAttention, fused kernels and quantization make models faster, and it is valuable for performance engineering roles.
Sources and further reading
- NVIDIA, CUDA C++ Programming Guide
- NVIDIA, CUDA C++ Best Practices Guide
- NVIDIA Developer Blog, An Even Easier Introduction to CUDA
- OpenAI, Triton documentation
- NVIDIA, CUTLASS on GitHub




Leave a Reply