CUDA Programming Model

Chapter 2 — Threads, blocks and grids: mapping work to the GPU

What you will learn

  • Why CUDA groups threads into blocks, and blocks into a grid
  • How each thread computes the element it owns, in 1D and 2D
  • How to catch launch and execution errors with one macro
  • The grid-stride loop: one kernel that works for any input size

The thread hierarchy

When you launch a kernel you create a grid. The grid is made of blocks, and each block is made of threads. Every thread runs the same kernel code; only its index values differ.

Why the middle layer? Blocks are the unit the hardware schedules:

  • A whole block runs on one streaming multiprocessor (SM). That is why threads in a block can share the SM's fast on-chip memory and wait for each other at a barrier (Chapters 3 and 5).
  • Blocks are independent. They can run in any order, at the same time or one after another. Because of that, the same program runs on a small GPU with 20 SMs and a large one with 140: the large GPU just runs more blocks at once.
grid: kernel<<<4, 8>>> — gridDim.x = 4, blockDim.x = 8blockIdx.x = 00011223344556677global indexblockIdx.x = 10819210311412513614715global indexblockIdx.x = 2016117218319420521622723global indexblockIdx.x = 3024125226327428529630731global indexhighlighted thread: blockIdx.x * blockDim.x + threadIdx.x = 2 * 8 + 3 = 19top numbers: threadIdx.x (restarts in every block) · bottom numbers: unique global index
threadIdx.x repeats in every block. Combine it with the block number to get an index that is unique across the grid.

Built-in index variables

VariableMeaning
threadIdxThis thread's position inside its block (.x, .y, .z)
blockIdxThis block's position inside the grid
blockDimThreads per block in each dimension (the second launch value)
gridDimBlocks in the grid in each dimension (the first launch value)

The launch values can be plain integers (1D) or dim3 values for 2D and 3D shapes. Limits that matter in practice: at most 1024 threads per block (the product of all three dimensions), and gridDim.x up to 231−1 while gridDim.y and gridDim.z stop at 65,535.

Choose a block size that is a multiple of 32. The hardware runs threads in groups of 32 called warps (Chapter 4), so a block of 100 threads still occupies four full warps. 128 or 256 threads is a good default; tune it later with a profiler.

Catching errors before they waste your afternoon

CUDA API functions return a cudaError_t. Kernel launches return nothing, so their errors arrive in two different ways:

  • Launch errors (an invalid configuration, such as 2048 threads per block) are reported by cudaGetLastError() right after the launch. The exact error name depends on the CUDA version; what matters is that it is not cudaSuccess.
  • Execution errors (such as an out-of-bounds memory access inside the kernel) happen later, on the GPU. They are reported by the next call that waits for the kernel, such as cudaDeviceSynchronize() or a cudaMemcpy.

A small macro handles both. From here on, every program in this course uses it. The program below launches with 2048 threads per block on purpose and shows the error being caught:

error_check.cu
1234567891011121314151617181920212223242526272829303132333435363738394041
#include <cstdio>
#include <cstdlib>

// Wrap every CUDA API call: print file, line and message, then stop.
#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 fill(int *out, int n) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) out[i] = i;
}

int main() {
    const int n = 4096;
    int *d_out;
    CUDA_CHECK(cudaMallocManaged(&d_out, n * sizeof(int)));

    // Invalid on purpose: the limit is 1024 threads per block.
    fill<<<2, 2048>>>(d_out, n);
    cudaError_t launchErr = cudaGetLastError();
    printf("bad launch  -> %s\n", cudaGetErrorString(launchErr));

    // A valid launch: check the launch, then check execution.
    fill<<<(n + 255) / 256, 256>>>(d_out, n);
    CUDA_CHECK(cudaGetLastError());
    CUDA_CHECK(cudaDeviceSynchronize());

    bool ok = (launchErr != cudaSuccess) && d_out[n - 1] == n - 1;
    printf("good launch -> out[%d] = %d\n", n - 1, d_out[n - 1]);
    printf(ok ? "PASS\n" : "FAIL\n");

    CUDA_CHECK(cudaFree(d_out));
    return 0;
}
Errors stick

Most execution errors, such as an illegal memory access, corrupt the whole CUDA context. Every later call then fails with the same error. Find the first failing call, not the last. compute-sanitizer ./app reports the exact kernel, thread and address of an invalid access; Chapter 4 shows how to use it.

The grid-stride loop

The SAXPY kernel in Chapter 1 used one thread per element, so the grid size depended on n. A more flexible pattern lets each thread handle several elements, stepping by the total number of threads in the grid:

cuda
12345
for (int i = blockIdx.x * blockDim.x + threadIdx.x;
     i < n;
     i += blockDim.x * gridDim.x) {
    y[i] = a * x[i] + y[i];
}

Why this is worth the extra lines:

  • Any grid size is correct. One block or a million, the loop covers every element exactly once. That makes debugging easy: launch <<<1, 1>>> and the kernel runs serially.
  • You can size the grid to the GPU, for example a few blocks per SM, instead of to the data.
  • Accesses stay efficient. In each pass, neighboring threads touch neighboring elements, the access pattern Chapter 7 shows is fastest.
grid_stride.cu
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
#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)

__global__ void saxpy(int n, float a, const float *x, float *y) {
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n;
         i += blockDim.x * gridDim.x)
        y[i] = a * x[i] + y[i];
}

int main() {
    const int n = 10000019;   // a prime: no block size divides it evenly
    float *x, *y;
    CUDA_CHECK(cudaMallocManaged(&x, n * sizeof(float)));
    CUDA_CHECK(cudaMallocManaged(&y, n * sizeof(float)));

    // Size the grid to the GPU, not to the data.
    int device, numSMs;
    CUDA_CHECK(cudaGetDevice(&device));
    CUDA_CHECK(cudaDeviceGetAttribute(&numSMs, cudaDevAttrMultiProcessorCount, device));
    int threads = 256, blocks = 4 * numSMs;

    int launches[][2] = { {blocks, threads}, {1, 32}, {1, 1} };  // all must give the same answer
    bool ok = true;
    for (auto &cfg : launches) {
        for (int i = 0; i < n; i++) { x[i] = i % 100; y[i] = 1.0f; }
        saxpy<<<cfg[0], cfg[1]>>>(n, 2.0f, x, y);
        CUDA_CHECK(cudaGetLastError());
        CUDA_CHECK(cudaDeviceSynchronize());

        int errors = 0;
        for (int i = 0; i < n; i++)
            if (fabsf(y[i] - (2.0f * (i % 100) + 1.0f)) > 1e-5f) errors++;
        printf("<<<%4d, %3d>>>  errors: %d\n", cfg[0], cfg[1], errors);
        ok = ok && errors == 0;
    }
    printf("%d SMs on this GPU\n", numSMs);
    printf(ok ? "PASS\n" : "FAIL\n");

    CUDA_CHECK(cudaFree(x));
    CUDA_CHECK(cudaFree(y));
    return 0;
}

Two-dimensional grids for images and matrices

Many problems have a 2D shape. Using a 2D grid lets each thread read its row and column directly instead of decoding them from one number. Memory is still one-dimensional, so a row-major image element lives at row * width + col.

image: width × height pixelsblock (1,1)col = blockIdx.x * blockDim.x + threadIdx.xrow = blockIdx.y * blockDim.y + threadIdx.ydashed blocks hang past the edge:guard with col < width && row < heightpixel lives at img[row * width + col]
A 2D grid of 2D blocks covering an image. The grid is rounded up in both directions.

The example below also introduces the other function qualifiers. A __device__ function runs on the GPU and is called from GPU code. Marking a function __host__ __device__ compiles it for both, so the CPU reference check can reuse exactly the same math as the kernel.

QualifierRuns onCalled from
__global__GPUHost (a launch). Must return void.
__device__GPUGPU code
__host__ (default)CPUCPU code
__host__ __device__BothEither; compiled twice
image_2d.cu
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
#include <cstdio>
#include <cstdlib>
#include <vector>

#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)

// Shared by GPU kernel and CPU reference.
__host__ __device__ unsigned char adjust(unsigned char p, float gain, int bias) {
    float v = p * gain + bias;
    return (unsigned char)(v < 0.f ? 0.f : (v > 255.f ? 255.f : v));   // clamp
}

__global__ void brighten(unsigned char *img, int width, int height, float gain, int bias) {
    int col = blockIdx.x * blockDim.x + threadIdx.x;
    int row = blockIdx.y * blockDim.y + threadIdx.y;
    if (col < width && row < height)                 // guard both directions
        img[row * width + col] = adjust(img[row * width + col], gain, bias);
}

int main() {
    const int width = 1000, height = 700;            // not multiples of 16 on purpose
    const size_t n = (size_t)width * height;
    unsigned char *img;
    CUDA_CHECK(cudaMallocManaged(&img, n));

    std::vector<unsigned char> ref(n);
    for (size_t i = 0; i < n; i++) { img[i] = (unsigned char)(i * 7 % 256); ref[i] = img[i]; }

    dim3 block(16, 16);                               // 256 threads
    dim3 grid((width + block.x - 1) / block.x,        // round up in x
              (height + block.y - 1) / block.y);      // and in y
    brighten<<<grid, block>>>(img, width, height, 1.5f, -20);
    CUDA_CHECK(cudaGetLastError());
    CUDA_CHECK(cudaDeviceSynchronize());

    size_t errors = 0;
    for (size_t i = 0; i < n; i++)
        if (img[i] != adjust(ref[i], 1.5f, -20)) errors++;
    printf("grid %u x %u blocks of %u x %u threads, mismatches: %zu\n",
           grid.x, grid.y, block.x, block.y, errors);
    printf(errors == 0 ? "PASS\n" : "FAIL\n");

    CUDA_CHECK(cudaFree(img));
    return 0;
}

Summary

  • A launch creates a grid of blocks of threads. A block runs on one SM; blocks are independent and may run in any order.
  • Global 1D index: blockIdx.x * blockDim.x + threadIdx.x. Round the grid up and guard with if (i < n).
  • Check cudaGetLastError() after a launch for configuration errors, and the next synchronizing call for execution errors.
  • Grid-stride loops make a kernel correct for any grid size and let you size the grid to the GPU.
  • For 2D data use dim3 blocks and grids, and guard both coordinates.

Exercises

1. Index by hand. With <<<5, 64>>>, which global index does thread 10 of block 3 own? Which block and thread own global index 200?

Solution

3 × 64 + 10 = 202. Index 200 belongs to block 200 / 64 = 3, thread 200 % 64 = 8.

2. Find the bug. This launch skips elements for some sizes. Which ones, and how do you fix it?

cuda
12
int blocks = n / 256;
saxpy<<<blocks, 256>>>(n, a, x, y);   // one-element-per-thread kernel
Solution

Integer division rounds down, so when n is not a multiple of 256 the last n % 256 elements get no thread. For n < 256 it launches zero blocks, which is an error. Use (n + 255) / 256, or switch to a grid-stride loop.

3. Transpose with a 2D grid. Write transpose(const float *in, float *out, int rows, int cols) where out has cols rows. Use 16×16 blocks and check the result on the CPU.

Solution
cuda
12345678
__global__ void transpose(const float *in, float *out, int rows, int cols) {
    int c = blockIdx.x * blockDim.x + threadIdx.x;   // column in 'in'
    int r = blockIdx.y * blockDim.y + threadIdx.y;   // row in 'in'
    if (r < rows && c < cols)
        out[c * rows + r] = in[r * cols + c];
}
// dim3 block(16, 16);
// dim3 grid((cols + 15) / 16, (rows + 15) / 16);

This version is correct but its writes are scattered. Chapter 7 makes it fast with shared memory.

Check your understanding

Block 7 needs a value that block 3 computes in the same kernel. Can it wait for it?

No. Blocks have no guaranteed order and may not even be running at the same time. Split the work into two kernel launches: the second launch starts only after the first one finishes.

Your kernel reads out of bounds, but cudaGetLastError() after the launch returns success. Why?

The launch itself was valid. The bad access happens while the kernel runs, after the launch call returned. It shows up at the next synchronizing call.

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 you'll take control of memory: explicit device allocations, copies, and the on-chip memories that make kernels fast. Continue to Memory Management.

Practice These Concepts

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

SAXPY: Single Precision A*X Plus Yeasy

Implement the BLAS SAXPY operation: y = a*x + y, where a is a scalar and x, y are vectors. This is one of the most fundamental GPU operations. Vector size N = 8192. Each thread handles one element.

Sign in to track your progress across challenges.