CUDA, one example at a time
GPU programming,
by example.
Small, complete CUDA programs that show you how threads, memory and streams actually behave — with reference output and diagrams you can play with.
Host code launches kernels. Hardware schedules blocks. Threads do the work.
Read it, run it, break it#
Rust by Example teaches Rust with small programs and lets the compiler fill in the gaps. This book does the same for CUDA. Every idea arrives as a complete program you can compile, a reference output block, and a short explanation of why the machine behaved that way.
The examples are small on purpose. A GPU has a lot of moving parts — grids, warps, shared memory, streams — and each one is easier to understand when it is the only new thing in the program.
Why a GPU is not a faster CPU#
A CPU is built to finish one instruction stream quickly. It spends most of its silicon on caches, branch prediction, and out-of-order execution. A GPU is built to finish millions of independent instruction streams at once, and it spends its silicon on lanes. When one group of threads stalls on memory, the SM switches to another group and keeps computing.
| CPU | GPU | |
|---|---|---|
| Cores | 8–64 fat cores | Thousands of lanes in tens–hundreds of SMs |
| Optimised for | Latency of one thread | Throughput of many threads |
| Branching | Cheap and well predicted | Divergence splits a warp into serial passes |
| Memory | Deep cache hierarchy | High bandwidth, high latency; hide it with warps |
| You write | A loop | A kernel, launched over a grid |
Here is the same operation written both ways. One scales an array of n floats on the CPU; the other runs as one thread per element on the GPU.
// CPU: one thread, one element at a time.
for (int i = 0; i < n; ++i) {
out[i] = 2.0f * in[i];
}
// GPU: n threads, one element each. The index is the whole trick.
__global__ void scale(const float* in, float* out, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
out[i] = 2.0f * in[i];
}
}The GPU version is not complicated — it is the same arithmetic. What changed is who executes it. scale<<<4096, 256>>> asks for 1,048,576 threads. Each one computes its own i and handles one element. No loop.
The whole model in four steps#
Every CUDA program you will write in this book follows the same shape:
- Allocate memory on the GPU and copy inputs over.
- Launch a kernel with an execution configuration:
kernel<<<blocks, threads>>>. - Synchronise — kernel launches return immediately.
- Copy results back and free.
float *d_in, *d_out;
cudaMalloc(&d_in, n * sizeof(float)); // 1. allocate
cudaMemcpy(d_in, h_in, n * sizeof(float),
cudaMemcpyHostToDevice); // copy in
scale<<<(n + 255) / 256, 256>>>(d_in, d_out, n); // 2. launch
cudaDeviceSynchronize(); // 3. wait
cudaMemcpy(h_out, d_out, n * sizeof(float),
cudaMemcpyDeviceToHost); // 4. copy out
cudaFree(d_in);Later chapters replace each of these steps with better tools — unified memory, streams, asynchronous copies — but the shape never changes.
What you need#
- An NVIDIA GPU (compute capability 5.0 or newer for the examples here; a few later chapters ask for 7.0+ or 9.0+).
- CUDA Toolkit 12.0 or newer, which gives you
nvcc. - Linux, Windows, or WSL. macOS no longer supports CUDA.
Check both halves of the stack before you start:
$ nvidia-smi --query-gpu=name,compute_cap --format=csv
name, compute_cap
NVIDIA GeForce RTX 4090, 8.9
$ nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Cuda compilation tools, release 12.4, V12.4.131No GPU handy? You can still read everything: each example ships with the output of a real run, and the interactive diagrams run entirely in your browser.
How to read this book#
- Code blocks are complete unless marked otherwise. Hit Copy and compile, or hit Run to replay the reference output.
- Green panels marked Key idea are the one thing worth remembering from a section.
- Widgets let you change grid sizes, warp masks, strides, and occupancy numbers to see the formula move.
- Exercises at the end of each chapter are small changes, not new projects. Do them.
The fastest way to learn this material is to predict what a program will print before you run it, then be wrong.
Where the material comes from#
This is an example-first companion to NVIDIA's CUDA Programming Guide, especially Part 1 — the introduction, programming model, and basics. The sequence is ours; the semantics are the guide's. When a chapter skips ahead (tile programming, clusters), it says so.
Ready? The next page is nine lines of CUDA and a compiler command.
<a class="btn-primary" href="hello-gpu.html">Hello, GPU →</a>