The CUDA programming model: threads, blocks, warps and SMs
How one kernel launch becomes thousands of threads, how they are grouped into blocks and warps, how blocks land on streaming multiprocessors, and how to write, launch, check and time your first real kernel: vector add, measured against the bandwidth limit.
By Sandip Maity, Applied AI Engineer
The last lesson ended with a program that printed eight lines in an unpredictable order. Let's work out exactly what happened, because everything else in this course builds on it.
#One launch, many threads
When you write hello<<<2, 4>>>(), you're asking the GPU to run the same function in 2 blocks of 4 threads. That's 8 copies of hello, all running the same code at roughly the same time. Each copy knows who it is through a few built-in variables:
| Variable | Meaning | In <<<2, 4>>> |
|---|---|---|
threadIdx.x |
This thread's index inside its block | 0 to 3 |
blockIdx.x |
This block's index in the grid | 0 or 1 |
blockDim.x |
Threads per block | 4 |
gridDim.x |
Blocks in the grid | 2 |
The whole launch is the grid. The grid is made of blocks, and blocks are made of threads. Each of those can be 1D, 2D or 3D (.x, .y, .z), which is convenient for images and matrices, but it's the same idea.
To give each thread its own element of an array, you combine them. The global index of a thread is .
Pick an element below and watch where it lands: which block, which thread, which warp, and which SM.
Threads per block
i = blockIdx.x × blockDim.x + threadIdx.x = 2 × 128 + 44
Grid (a few of the blocks)
Block 2: 4 warps
Warp 1: 32 lanes
blockIdx.x
2
threadIdx.x
44
warp in block
1
lane
12
SM (illustrative)
2
One thread per element, 1D launch. Blocks are handed to SMs by the hardware scheduler; the SM shown assumes simple round-robin placement on a 40-SM T4, which real hardware does not promise.
#Warps: the unit the hardware actually runs
Here's the part that isn't in the launch syntax. The GPU doesn't schedule single threads. It groups every 32 consecutive threads of a block into a warp, and a warp is what the hardware issues instructions for. All 32 threads in a warp execute the same instruction at the same time, each on its own data. NVIDIA calls this SIMT: single instruction, multiple threads.
Three consequences follow, and you'll meet each one again:
- Pick block sizes in multiples of 32. A block of 100 threads is 4 warps, and the last one has 28 idle lanes.
- Divergence costs time. If some threads in a warp take an
ifand others take theelse, the warp runs both paths, one after the other, with the inactive threads masked off. Branches that split warps are slow; branches where whole warps go the same way are free. - Memory is fetched per warp. When 32 threads load 32 neighbouring floats, the hardware can serve them with a few wide transactions. When they load scattered addresses, it can't. That's coalescing, the topic of the next lesson.
#Blocks land on SMs
A GPU is a collection of streaming multiprocessors (SMs). The T4 has 40; an H100 has 132. When you launch a grid, a hardware scheduler hands out blocks to SMs. Each block lives on exactly one SM from start to finish, and an SM can hold several blocks at once if it has room for their threads, registers and shared memory.
| T4 | H100 SXM | |
|---|---|---|
| SMs | 40 | 132 |
| Max threads per SM | 1,024 | 2,048 |
| Max blocks per SM | 16 | 32 |
| Max threads per block | 1,024 | 1,024 |
Why blocks matter beyond bookkeeping:
- Threads in one block can cooperate. They share fast on-chip shared memory and can wait for each other with
__syncthreads(). Threads in different blocks can't do either (without special launch modes). - Blocks must be independent. The hardware runs them in any order, on any SM, possibly not all at once. Your code must give the right answer whatever the order. That's why the
hellooutput was jumbled. - Too few blocks waste the GPU. A grid with 20 blocks on a 40-SM T4 leaves half the SMs idle, however hard each block works. You want at least a few blocks per SM.
#Your first real kernel: vector add
Here's a complete program. Read it once top to bottom; the interesting part is only four lines.
// vadd.cu: c = a + b, timed with CUDA events
#include <cstdio>
#include <cstdlib>
#define CHECK(x) do { cudaError_t e = (x); if (e != cudaSuccess) { \
printf("CUDA error %s at %s:%d\n", cudaGetErrorString(e), __FILE__, __LINE__); exit(1); } } while (0)
__global__ void vadd(const float* a, const float* b, float* c, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) c[i] = a[i] + b[i];
}
int main() {
const int n = 1 << 26; // 64M floats, 256 MB per array
const size_t bytes = n * sizeof(float);
float *a, *b, *c;
CHECK(cudaMalloc(&a, bytes)); CHECK(cudaMalloc(&b, bytes)); CHECK(cudaMalloc(&c, bytes));
CHECK(cudaMemset(a, 0, bytes)); CHECK(cudaMemset(b, 0, bytes));
const int threads = 256;
const int blocks = (n + threads - 1) / threads; // round up
cudaEvent_t start, stop;
CHECK(cudaEventCreate(&start)); CHECK(cudaEventCreate(&stop));
vadd<<<blocks, threads>>>(a, b, c, n); // warm-up
CHECK(cudaGetLastError());
CHECK(cudaEventRecord(start));
const int reps = 20;
for (int r = 0; r < reps; r++) vadd<<<blocks, threads>>>(a, b, c, n);
CHECK(cudaEventRecord(stop));
CHECK(cudaEventSynchronize(stop));
float ms; CHECK(cudaEventElapsedTime(&ms, start, stop)); ms /= reps;
double gbs = 3.0 * bytes / (ms / 1e3) / 1e9;
printf("%.3f ms per call, %.1f GB/s\n", ms, gbs);
}!nvcc -O3 -arch=sm_75 -o vadd vadd.cu && ./vaddThe pieces worth noticing:
__global__marks a function that runs on the GPU and is launched from the CPU.- The round-up
(n + threads - 1) / threadsgives enough blocks to cover every element. Theif (i < n)check stops the spare threads in the last block from writing past the end. CHECKeverything. CUDA calls fail quietly: a bad launch just returns an error code that nobody reads.cudaGetLastError()after a launch catches launch failures such as asking for too many threads per block.- Warm up first. The first launch pays one-off costs (loading the kernel, setting up the context). Time later runs.
- Events, not CPU timers. A launch returns immediately; the CPU doesn't wait for the GPU. Events are timestamps the GPU records in its own queue, so the gap between them is GPU time.
#What to expect
Vector add does one addition for every 12 bytes it moves (two 4-byte reads and one 4-byte write). That's about 0.08 FLOPs per byte, far below any GPU's balance point, so it's completely bandwidth-bound (roofline). The best possible time is the bytes divided by the bandwidth:
You won't hit 320 GB/s. The spec is a peak; even a perfect copy kernel reaches a fraction of it, and how large a fraction depends on the GPU. Write down your number: it's your practical bandwidth ceiling, and you'll compare every later bandwidth-bound kernel against it.
#Grid-stride loops
The kernel above launches one thread per element: 262,144 blocks for 64 million floats. That's fine, but a common alternative launches a fixed number of blocks and has each thread loop:
__global__ void vadd_strided(const float* a, const float* b, float* c, int n) {
for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += blockDim.x * gridDim.x)
c[i] = a[i] + b[i];
}
// launch with, say, 4 blocks per SM: vadd_strided<<<40 * 4, 256>>>(a, b, c, n);Each thread starts at its global index and jumps forward by the total number of threads in the grid. Neighbouring threads still touch neighbouring elements on every pass, so memory access stays efficient. Grid-stride loops work for any n with any grid size, and they amortise per-thread setup. You'll see this pattern all over production kernels.
#Waves and tails
When a grid has more blocks than the GPU can hold at once, blocks run in waves. Say each SM can hold 4 blocks of 256 threads (1,024 threads, the T4's limit). Then the T4 runs blocks at once. A grid of 170 blocks runs as one full wave of 160 and a second wave of only 10, during which 150 block slots sit idle.
For vector add with 262,144 blocks this "tail" is negligible. For small grids, which is exactly what decode produces at batch 1, it can be the dominant cost. You saw the same effect with matmul tiles in kernel selection: too few tiles, or a ragged last wave, and the GPU is under-used.
#The CPU and GPU are separate machines
It's easy to forget that your program runs on two processors with two memories:
cudaMallocallocates GPU memory. A pointer fromcudaMallocis not valid on the CPU, and amallocpointer isn't valid on the GPU. Dereference the wrong one and you'll get a crash or, worse, garbage.cudaMemcpymoves data across PCIe, which is roughly 20 to 30 times slower than GPU memory on a T4. Keep data on the GPU and move it as rarely as possible.- Launches are asynchronous. The CPU queues kernels into a stream and carries on. Calls like
cudaMemcpy(back to the host),cudaDeviceSynchronizeandcudaEventSynchronizemake the CPU wait. You'll use this deliberately in streams and CUDA graphs.
PyTorch hides all of this, which is why torch.cuda.synchronize() shows up in every honest benchmark script: without it, you time how long it took to queue the work.
#Finding bugs
GPU bugs are often silent. Two tools catch most of them:
!compute-sanitizer ./vaddcompute-sanitizer (part of the CUDA toolkit) reports out-of-bounds reads and writes, race conditions and uninitialised memory. Run it whenever a kernel gives wrong answers. Try deleting the if (i < n) check and setting n to something that isn't a multiple of 256: the sanitizer will point straight at the bad write.
Also always compare against a reference. For vector add the reference is trivial; for the kernels later in this course it'll be a PyTorch call, and you'll check with a tolerance, because floating-point results change slightly when you change the order of operations.
#What you can now do
- Explain grids, blocks, threads and warps, and how blocks are placed on SMs.
- Compute a thread's global index and cover any array size safely.
- Launch, error-check and time a kernel with CUDA events.
- Work out the best possible time for a bandwidth-bound kernel and compare it with your measurement.
#Common mistakes
- Timing the launch, not the kernel. Always synchronise, or use events.
- Forgetting the bounds check. It works for "nice" sizes and corrupts memory for others.
- Not checking errors. A launch with 2,048 threads per block fails silently, and your timing then measures nothing.
- Block sizes that aren't multiples of 32. You pay for whole warps either way.
- Tiny grids. Fewer blocks than SMs leaves hardware idle, whatever the kernel does.
- Moving data to the CPU in the middle of a loop. Each copy is slow and forces a synchronisation.
#Exercise
- A kernel is launched as
<<<1000, 192>>>. How many threads and how many warps are there? With one thread per element, which block and whichthreadIdx.xhandle element 50,000? - Run
vaddwith 32, 128, 256 and 1,024 threads per block. Does the bandwidth change much? Why might it not? - Your vector add measures 3.2 ms on a T4 for the 64M-float case. What fraction of the 320 GB/s peak is that?
- A grid has 41 blocks and each block takes the same time. Each T4 SM can hold only one of these blocks. How long does the grid take compared with a grid of 40 blocks?
Show answers
- threads, and warps per block, so 6,000 warps. Element 50,000 is handled by block , and .
- Usually not much, because vector add is limited by memory, not by how threads are grouped, as long as there are enough warps in flight to keep memory busy. Very small blocks (32 threads) can be slower because of the cap on blocks per SM: 16 blocks of 32 threads is only 512 threads per T4 SM.
- , which is of peak.
- Twice as long: the 41st block runs in a second wave on its own, while 39 SMs sit idle.
#Going deeper
- Next: memory coalescing and bandwidth-bound kernels, where you'll see why the order in which threads touch memory can change speed by 8 times.
- The CUDA C++ Programming Guide's chapter on the programming model is the reference for everything in this lesson.
Quick quiz
+10 XP per correct answer, +25 XP for a perfect score
1. A kernel is launched with 256 threads per block and 4,096 blocks. How many warps is that?
2. Why does vector add need the check if (i < n)?
3. Half the threads in a warp take the if branch and half take the else. What happens?
4. Vector add on 64 million floats moves 768 MB. On a 320 GB/s T4, what is the best possible time?
5. Why time a kernel with CUDA events rather than a CPU timer around the launch?
Up next · 24 min · Pro, first part free
Memory coalescing and bandwidth-bound kernels: copy, stride and transpose
How a warp's 32 loads become 32-byte memory sectors, why strided access can waste most of your bandwidth, how vectorised loads help, and how to write a matrix transpose that reads and writes efficiently using shared memory without bank conflicts.
Continue →Found this useful?
Send it to someone who is learning the same thing.
Articles that build on this lesson