The CUDA Execution Model

Chapter 4 — SMs, warps, latency hiding and occupancy

What you will learn

  • How blocks are spread over the SMs and split into warps
  • How the GPU hides memory latency, and why it needs many threads to do it
  • What branch divergence costs, measured
  • Occupancy: what limits it, how to compute it, and when it matters
  • How to time kernels correctly and find memory bugs with compute-sanitizer

Chapters 1–3 described the programming model, the view CUDA gives you. This chapter is about the hardware underneath. You can write correct kernels without it, but every performance rule in the rest of the course follows from these few facts.

From grid to SMs

A GPU is built from streaming multiprocessors (SMs). A laptop GPU may have 20–40; a data-center GPU over 100. When you launch a kernel, a hardware scheduler hands out blocks to SMs. An SM can hold several blocks at once, as long as it has enough registers, shared memory and thread slots for all of them. A block stays on its SM until all of its threads finish, then its slot goes to the next waiting block.

If a grid has more blocks than fit at once, they run in waves. A grid of 1,000 blocks on a GPU that fits 160 at a time runs in 7 waves, and the last wave is only partly full. That is one reason to prefer many small blocks over a few big ones, and why grid-stride kernels often size the grid as a multiple of the SM count.

Warps: the unit of execution

Inside an SM, a block's threads are split into warps of 32 consecutive threads. Threads are numbered with x varying fastest, so for a 1D block, warp 0 is threads 0–31, warp 1 is threads 32–63, and so on. The SM's warp schedulers pick a warp that is ready and issue its next instruction for all its active threads at once. NVIDIA calls this SIMT: single instruction, multiple threads.

a block of 256 threads = 8 warps of 32warp 0warp 1warp 2warp 3warp 4warp 5warp 6warp 7one warp scheduler over timew0w1w2w3w0w4w1w5w2w6w0 waits for a memory loadEach slot is one issued instruction. While warp 0 waits for memory, the scheduler issues from other warps.
The scheduler issues from whichever warp is ready, so waiting costs nothing as long as some warp has work.

Latency hiding

A load from device memory takes several hundred cycles. A CPU core would try to avoid that wait with large caches and speculation. A GPU simply works on something else: the warp that issued the load is set aside, and the scheduler issues from another warp. Switching costs nothing, because every resident warp keeps its registers on the SM the whole time.

That only works if there is another ready warp. To keep the memory system busy, you need enough loads in flight to cover the latency. As a rough rule, bandwidth × latency = bytes that must be in flight. With hundreds of GB/s and hundreds of nanoseconds of latency, that means tens of kilobytes per SM. You get there with many resident warps (occupancy), with several independent loads per thread (instruction-level parallelism), or both.

Branch divergence

All active threads of a warp execute the same instruction. When threads of one warp take different sides of a branch, the warp runs the first path with the other threads switched off, then the second path, then the threads continue together. Both paths cost time. A branch on a condition that is the same for the whole warp, such as one based on threadIdx.x / 32, costs almost nothing.

The program below gives every thread the same amount of work, split into two paths. Only the choice of path differs: by odd and even thread (divergent within every warp) or by odd and even warp (uniform within each warp).

divergence.cu
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
#include <cstdio>
#include <cstdlib>
#include <cmath>

#define CUDA_CHECK(call)                                                   \
    do {                                                                   \
        cudaError_t err_ = (call);                                         \
        if (err_ != cudaSuccess) {                                         \
            fprintf(stderr, "CUDA error %s at %s:%d\n",                     \
                    cudaGetErrorString(err_), __FILE__, __LINE__);         \
            exit(1);                                                       \
        }                                                                  \
    } while (0)

#define ITERS 4000

__host__ __device__ float pathA(float x) { for (int k = 0; k < ITERS; k++) x = fmaf(x, 0.9999f, 0.0001f); return x; }
__host__ __device__ float pathB(float x) { for (int k = 0; k < ITERS; k++) x = fmaf(x, 1.0001f, -0.0001f); return x; }

// Odd and even threads take different paths: every warp runs both paths.
__global__ void divergent(float *v, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i >= n) return;
    v[i] = (threadIdx.x % 2) ? pathA(v[i]) : pathB(v[i]);
}

// Odd and even WARPS take different paths: each warp runs only one.
__global__ void uniform(float *v, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i >= n) return;
    v[i] = ((threadIdx.x / 32) % 2) ? pathA(v[i]) : pathB(v[i]);
}

int main() {
    const int n = 1 << 20, threads = 256, blocks = n / threads;
    const size_t bytes = n * sizeof(float);
    float *h = (float *)malloc(bytes), *out = (float *)malloc(bytes), *d;
    for (int i = 0; i < n; i++) h[i] = (i % 7) * 0.1f;
    CUDA_CHECK(cudaMalloc(&d, bytes));

    cudaEvent_t a, b;
    CUDA_CHECK(cudaEventCreate(&a)); CUDA_CHECK(cudaEventCreate(&b));
    bool ok = true;
    for (int version = 0; version < 2; version++) {
        for (int rep = 0; rep < 2; rep++) {          // rep 0 is a warm-up
            CUDA_CHECK(cudaMemcpy(d, h, bytes, cudaMemcpyHostToDevice));
            CUDA_CHECK(cudaEventRecord(a));
            if (version == 0) divergent<<<blocks, threads>>>(d, n);
            else              uniform<<<blocks, threads>>>(d, n);
            CUDA_CHECK(cudaEventRecord(b));
            CUDA_CHECK(cudaEventSynchronize(b));
        }
        float ms; CUDA_CHECK(cudaEventElapsedTime(&ms, a, b));
        CUDA_CHECK(cudaMemcpy(out, d, bytes, cudaMemcpyDeviceToHost));

        int errors = 0;                              // spot-check every 61st element on the CPU
        for (int i = 0; i < n; i += 61) {
            int t = i % threads;
            bool takeA = version == 0 ? (t % 2) : ((t / 32) % 2);
            float ref = takeA ? pathA(h[i]) : pathB(h[i]);
            if (fabsf(out[i] - ref) > 1e-4f) errors++;
        }
        printf("%-9s branch: %6.3f ms, errors: %d\n", version == 0 ? "divergent" : "uniform", ms, errors);
        ok = ok && errors == 0;
    }
    printf(ok ? "PASS\n" : "FAIL\n");
    CUDA_CHECK(cudaFree(d));
    free(h); free(out);
    return 0;
}

Expect the divergent version to take about twice as long. Divergence matters when the branches do substantial work and split warps often. A short if that guards a single assignment, or the if (i < n) bounds check, which only splits the last warp, is not worth worrying about.

Warps are not lockstep

Older tutorials say the threads of a warp "execute in lockstep", so code inside a warp needs no synchronization. That has not been true since Volta (2017). With independent thread scheduling, each thread has its own program counter. The hardware may interleave the two sides of a branch and reconverge threads whenever it likes. Code that relies on implicit lockstep, such as the old volatile warp-reduction trick, is a data race on current GPUs.

If threads of a warp communicate through memory, synchronize them with __syncwarp(), or better, exchange values directly with warp shuffle functions such as __shfl_down_sync(mask, value, offset). The mask argument names the threads that participate. Chapter 5 uses both.

Occupancy

Occupancy is the number of warps resident on an SM divided by the most the SM can hold (for example 48 or 64 warps, depending on the architecture). Each resident block claims resources, and whichever runs out first sets the limit:

  • Registers. An SM has 65,536 32-bit registers. At 32 registers per thread, 2,048 threads fit; at 128 registers per thread, only 512.
  • Shared memory. A block that uses 48 KB of shared memory leaves room for only a few such blocks per SM.
  • Block and thread slots. An SM holds a limited number of blocks (16–32), so tiny blocks of 32 threads can leave thread slots unused.

You don't have to compute this by hand. The CUDA runtime does it for you, and the program below prints your GPU's limits and the occupancy of a kernel at several block sizes and shared-memory amounts. It uses cudaDeviceGetAttribute, which works across CUDA versions; some fields of the older cudaDeviceProp struct, such as memoryClockRate, were removed in CUDA 13.

occupancy.cu
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
#include <cstdio>
#include <cstdlib>

#define CUDA_CHECK(call)                                                   \
    do {                                                                   \
        cudaError_t err_ = (call);                                         \
        if (err_ != cudaSuccess) {                                         \
            fprintf(stderr, "CUDA error %s at %s:%d\n",                     \
                    cudaGetErrorString(err_), __FILE__, __LINE__);         \
            exit(1);                                                       \
        }                                                                  \
    } while (0)

__global__ void scale(float *v, int n) {
    extern __shared__ float scratch[];       // dynamic shared memory, size chosen at launch
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) v[i] *= 2.0f;
    if (blockDim.x == 0) scratch[0] = 0.0f;  // keep the array referenced
}

int attr(cudaDeviceAttr a, int dev) { int v; CUDA_CHECK(cudaDeviceGetAttribute(&v, a, dev)); return v; }

int main() {
    int dev; CUDA_CHECK(cudaGetDevice(&dev));
    cudaDeviceProp p; CUDA_CHECK(cudaGetDeviceProperties(&p, dev));

    int sms        = attr(cudaDevAttrMultiProcessorCount, dev);
    int maxThrSM   = attr(cudaDevAttrMaxThreadsPerMultiProcessor, dev);
    int regsSM     = attr(cudaDevAttrMaxRegistersPerMultiprocessor, dev);
    int smemSM     = attr(cudaDevAttrMaxSharedMemoryPerMultiprocessor, dev);
    int memClkKHz  = attr(cudaDevAttrMemoryClockRate, dev);
    int busBits    = attr(cudaDevAttrGlobalMemoryBusWidth, dev);

    printf("%s, compute capability %d.%d\n", p.name, p.major, p.minor);
    printf("SMs: %d | max threads/SM: %d (%d warps) | registers/SM: %d | shared/SM: %d KB\n",
           sms, maxThrSM, maxThrSM / 32, regsSM, smemSM / 1024);
    printf("theoretical memory bandwidth: ~%.0f GB/s\n", 2.0 * memClkKHz * 1e3 * (busBits / 8) / 1e9);

    printf("\noccupancy of 'scale' (resident warps / max warps per SM):\n");
    printf("%-12s %8s %8s %8s\n", "block size", "0 KB", "16 KB", "40 KB");
    for (int bs : {32, 64, 128, 256, 512, 1024}) {
        printf("%-12d", bs);
        for (int kb : {0, 16, 40}) {
            int blocksPerSM;
            CUDA_CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&blocksPerSM, scale, bs, kb * 1024));
            printf(" %7.0f%%", 100.0 * blocksPerSM * bs / maxThrSM);
        }
        printf("\n");
    }

    int minGrid, bestBlock;
    CUDA_CHECK(cudaOccupancyMaxPotentialBlockSize(&minGrid, &bestBlock, scale, 0, 0));
    printf("\nruntime suggestion: block size %d, at least %d blocks to fill the GPU\n", bestBlock, minGrid);
    return 0;
}
Occupancy is a means, not a goal

Occupancy only matters as a way to hide latency. A kernel that keeps several independent loads or multiply-adds in flight per thread can reach full speed at 25–50% occupancy, and giving each thread more registers to do that is often the better trade. Chapter 8's fastest matrix multiply runs at deliberately modest occupancy. Use occupancy to explain a slow kernel, not as a score to maximize.

You can cap register use per thread with __launch_bounds__(maxThreadsPerBlock) on a kernel, or globally with nvcc -maxrregcount=N. If the compiler runs out of registers, it spills to local memory, which lives in device memory and is slow. Compile with -Xptxas -v to see registers and spills per kernel.

Timing kernels correctly

Because launches are asynchronous, a CPU timer around a launch measures only how long it took to queue the kernel. Use CUDA events: markers that the GPU timestamps when it reaches them in the stream.

cuda
1234567891011121314
cudaEvent_t start, stop;
cudaEventCreate(&start);
cudaEventCreate(&stop);

kernel<<<grid, block>>>(args);          // 1. warm-up: first launch pays one-time setup
cudaEventRecord(start);                 // 2. markers go into the same stream as the work
for (int r = 0; r < 20; r++)            // 3. repeat to average out noise
    kernel<<<grid, block>>>(args);
cudaEventRecord(stop);
cudaEventSynchronize(stop);             // 4. wait until the GPU reaches 'stop'

float ms;
cudaEventElapsedTime(&ms, start, stop);
printf("%.3f ms per launch\n", ms / 20);

Then turn the time into a rate you can compare with the hardware: effective bandwidth = bytes read + bytes written, divided by time. A kernel that reads and writes 128 MB in 0.5 ms moves 256 GB/s. Compare that number with the theoretical bandwidth the occupancy program printed. Chapter 7 builds on this.

Finding memory bugs

An out-of-bounds access in a kernel often does not crash. Allocations are rounded up, so reading one element past the end may return garbage silently. compute-sanitizer, part of the CUDA Toolkit, instruments your program and reports every invalid access with the kernel, thread and address:

terminal
1234567891011
nvcc -g -lineinfo buggy.cu -o buggy
compute-sanitizer ./buggy                    # memcheck: out-of-bounds and misaligned accesses
compute-sanitizer --tool racecheck ./buggy   # shared-memory data races
compute-sanitizer --tool initcheck ./buggy   # reads of uninitialized device memory
compute-sanitizer --tool synccheck ./buggy   # invalid __syncthreads / __syncwarp usage

# Typical report:
# ========= Invalid __global__ read of size 4 bytes
# =========     at add(const float *, const float *, float *, int)+0x70 in buggy.cu:5
# =========     by thread (255,0,0) in block (3,0,0)
# =========     Address 0x7f2a3e000400 is out of bounds

Other tools worth knowing: printf inside kernels (output appears at the next synchronization), -G for full device debug info with cuda-gdb or the Nsight debuggers (it disables optimizations, so don't time a -G build), and -lineinfo, which maps profiler and sanitizer results to source lines at no runtime cost.

Summary

  • Blocks are assigned to SMs as resources allow and run in waves. A block stays on one SM until it finishes.
  • A warp is 32 consecutive threads. The SM issues instructions per warp and switches between ready warps for free.
  • Latency is hidden by having enough work in flight: many warps, several independent operations per thread, or both.
  • Divergent branches within a warp run one after the other. Warp-uniform branches are cheap.
  • Since Volta, warps are not guaranteed to run in lockstep. Use __syncwarp() or *_sync shuffles.
  • Occupancy is limited by registers, shared memory and slots. It is a tool for explaining performance, not a target.
  • Time with CUDA events, after a warm-up, over several repetitions. Find invalid accesses with compute-sanitizer.

Exercises

1. Waves. A GPU has 40 SMs and each SM fits 6 blocks of your kernel. How many waves does a launch of 1,000 blocks need, and how full is the last wave?

Solution

40 × 6 = 240 blocks per wave. 1,000 / 240 = 4.17, so 5 waves, with only 40 blocks (17%) in the last one. Changing the grid to 960 or 1,200 blocks, or using a grid-stride loop with 240 blocks, removes the mostly empty tail.

2. Partial divergence. In divergence.cu, change the divergent condition to threadIdx.x % 32 < 4. Predict the time compared with the uniform version, then run it.

Solution

Still about twice the uniform time. Each warp has 4 threads on path A and 28 on path B, so every warp still runs both paths in full. What matters is whether a warp splits, not how many threads go each way.

3. Shared memory limits occupancy. In the occupancy table, why does the 40 KB column drop so sharply compared with the 0 KB column?

Solution

With 40 KB of shared memory per block, only as many blocks fit as the SM's shared memory allows, typically 1–2 on consumer GPUs. With small blocks that means very few resident warps. Larger blocks recover some occupancy because each block brings more warps for the same shared memory.

Check your understanding

Why can a GPU switch between warps without saving and restoring registers?

Every resident warp has its own registers on the SM for its whole lifetime. Switching only changes which warp the scheduler issues from.

A kernel runs at 30% occupancy and already reaches 90% of peak memory bandwidth. Should you try to raise occupancy?

No. Latency is already hidden, since the kernel is close to the hardware limit. More occupancy cannot make it much faster.

Further reading & credits

The chapter order and topic coverage of this course draw on the OLCF / NERSC CUDA Training Series, the NVIDIA Accelerated Computing Hub CUDA C++ tutorial, the GPU MODE lectures (Apache-2.0) and Simon Boehm's CUDA matrix multiplication worklog (code MIT). The text and example programs on this page are original and were tested on NVIDIA Turing and Ampere GPUs.

Next: making threads cooperate safely, with barriers, atomics and warp shuffles. Continue to Synchronization.

Practice These Concepts

Reinforce what you just learned with hands-on GPU coding challenges.

Matrix Multiplicationmedium

Implement a simple 2D matrix multiplication kernel. Multiply two NxN matrices where N = 64. Each thread computes one output element.

Sign in to track your progress across challenges.