Introduction to CUDA

Chapter 1 — Why GPUs are fast, and your first CUDA programs

What you will learn

  • Why a GPU wins on some workloads and loses on others
  • The host/device split every CUDA program follows
  • How to write, launch and wait for a kernel
  • Why kernel launches are asynchronous, and what that means for your code

Latency versus throughput

A CPU core is built to finish one stream of instructions as quickly as possible. Most of its silicon goes to large caches, branch prediction and out-of-order execution: machinery that hides the time a single thread spends waiting. That is a latency-optimized design.

A GPU makes the opposite trade. It has many simple arithmetic lanes and small caches, and it keeps thousands of threads resident at once. When one group of threads stalls on a memory load, the hardware switches to another group that is ready, in a single cycle. No one thread runs faster, but the total amount of finished work per second is far higher. That is a throughput-optimized design.

CPU — few large corescore + controlcore + controlcore + controlcore + controllarge cacheGPU — many SMs, thousands of lanessmall shared L2 cache
A CPU spends its transistors making a few threads fast. A GPU spends them on many streaming multiprocessors (SMs), each running many threads.

When the GPU wins, and when it doesn't

A workload benefits from a GPU when it has three properties:

  1. Lots of independent work. Millions of pixels, matrix elements or particles that can be processed at the same time.
  2. Enough work per byte moved. Data has to reach the GPU over PCIe, which is roughly 10–30× slower than the GPU's own memory. Adding two numbers per transfer will not pay for the trip. Multiplying large matrices, where each value is reused hundreds of times, will.
  3. Data that stays on the GPU. Real applications copy data in once, run many kernels over it, and copy back only the result.
A GPU does not speed up everything

Short loops, code where every step depends on the previous one, and small inputs usually run faster on the CPU. Always compare against a good CPU version and measure the whole program, including copies, not only the kernel.

The shape of a CUDA program

CUDA calls the CPU and its memory the host, and the GPU and its memory the device. A CUDA program is an ordinary C++ program that runs on the host. At chosen points it asks the device to run a kernel: a function executed by many GPU threads at once. Almost every CUDA program follows this sequence:

1. allocate2. copy input3. launch kernel4. copy result5. freehost code drives every steponly step 3 runs on the GPU's threads
The five steps of a typical CUDA program.

Your first kernel

Press Run to compile and execute this on a GPU. It launches 2 blocks of 4 threads, and every thread prints its own coordinates.

hello.cu
12345678910111213
#include <cstdio>

// __global__ marks a kernel: it runs on the GPU and is launched from the CPU.
__global__ void hello() {
    printf("Hello from block %d, thread %d\n", blockIdx.x, threadIdx.x);
}

int main() {
    hello<<<2, 4>>>();        // 2 blocks x 4 threads = 8 threads
    cudaDeviceSynchronize();  // wait for the GPU before the program exits
    printf("Kernel finished\n");
    return 0;
}
  • __global__ tells the compiler to build hello for the GPU.
  • hello<<<2, 4>>>() is a launch. The values inside the angle brackets are the execution configuration: the number of blocks, then the number of threads in each block.
  • blockIdx.x and threadIdx.x are built-in variables that are different in every thread. They are how a thread finds out which part of the work is its own.
  • cudaDeviceSynchronize() makes the CPU wait until all previously launched GPU work has finished.
Run it twice

The order of the lines can change between runs. Blocks are independent and the GPU may run them in any order. Never write code that depends on one block running before another.

Kernel launches are asynchronous

A launch only queues work for the GPU. The call returns to the CPU right away, often before any GPU thread has started. Remove the cudaDeviceSynchronize() from the program above and you will usually see no GPU output at all: main returns and the process exits before the kernel runs.

This is a feature. While the GPU works, the CPU is free to prepare the next batch. But it means you must synchronize before you read results or measure time. Some calls synchronize for you: a regular cudaMemcpy waits for earlier work in the same stream to finish before it copies. Chapter 6 uses this asynchrony to overlap copies with computation.

A kernel that does real work

Printing is fun, but kernels exist to transform data. The classic first example is SAXPY ("single-precision a·x plus y"): y[i] = a * x[i] + y[i] for every i. Each element is independent, so we give every thread exactly one.

To keep this first example short it uses unified memory (cudaMallocManaged), memory that both CPU and GPU can access through the same pointer. Chapter 3 shows explicit allocation and copies, which give you more control.

saxpy.cu
1234567891011121314151617181920212223242526272829303132
#include <cstdio>
#include <cmath>

__global__ void saxpy(int n, float a, const float *x, float *y) {
    int i = blockIdx.x * blockDim.x + threadIdx.x;  // this thread's element
    if (i < n)                                      // the last block may be partly unused
        y[i] = a * x[i] + y[i];
}

int main() {
    const int n = 1 << 20;   // about one million elements
    float *x, *y;
    cudaMallocManaged(&x, n * sizeof(float));
    cudaMallocManaged(&y, 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;      // round up
    saxpy<<<blocks, threads>>>(n, 3.0f, x, y);
    cudaDeviceSynchronize();                        // wait before the CPU reads y

    // Check every element against the expected value 3*1 + 2 = 5.
    int errors = 0;
    for (int i = 0; i < n; i++)
        if (fabsf(y[i] - 5.0f) > 1e-6f) errors++;
    printf("%d blocks x %d threads, errors: %d\n", blocks, threads, errors);
    printf(errors == 0 ? "PASS\n" : "FAIL\n");

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

Three lines carry the whole idea of data-parallel programming, and Chapter 2 is about them:

  • blockIdx.x * blockDim.x + threadIdx.x turns "which block, which thread" into one global element number.
  • (n + threads - 1) / threads rounds the number of blocks up, so every element gets a thread.
  • if (i < n) stops the extra threads in the last block from touching memory past the end of the arrays.
Habit worth keeping

Every runnable program in this course checks its own answer against a CPU result and prints PASS or FAIL. GPU bugs are often silent: a wrong index produces plausible-looking numbers. A check that compares every element catches them.

How CUDA code is compiled

CUDA source files end in .cu and are compiled with nvcc. It splits the file in two: host code goes to your normal C++ compiler, and device code is compiled for the GPU.

StageWhat it is
PTXA portable, assembly-like virtual instruction set. The driver can compile it for GPUs that did not exist when you built your program.
SASSThe real machine code for one GPU architecture, for example sm_75 (Turing) or sm_86 (Ampere consumer cards).
Fat binaryThe executable can contain SASS for several architectures plus PTX as a fallback.
terminal
123456
# Build for the GPU in this machine and run
nvcc -O2 -arch=native saxpy.cu -o saxpy
./saxpy

# Build SASS for Turing (sm_75) plus PTX that newer GPUs can JIT-compile
nvcc -O2 -arch=sm_75 saxpy.cu -o saxpy

To work locally you need an NVIDIA GPU, a recent driver and the CUDA Toolkit. Chapter 0, Installing CUDA, walks through it. You can skip that for now: the Playground compiles and runs your code on a GPU from the browser.

Summary

  • GPUs trade single-thread speed for throughput: thousands of threads, with fast switching to hide memory latency.
  • They win when there is lots of independent work, enough math per byte moved, and data that stays on the device.
  • A kernel is a __global__ function launched with <<<blocks, threadsPerBlock>>>; every thread runs it with different index values.
  • Launches are asynchronous. Synchronize before you read results or stop a timer.

Exercises

1. Count the lines. Change the hello launch to <<<3, 5>>>. Predict how many lines the GPU prints, then run it.

Solution

3 blocks × 5 threads = 15 lines, with block numbers 0–2 and thread numbers 0–4, in no guaranteed order.

2. Break it on purpose. In saxpy.cu, change the launch to saxpy<<<blocks / 2, threads>>>. What does the check report, and why?

Solution

Only half the elements get a thread, so the other half keep their old value (2.0 instead of 5.0). The check reports 524,288 errors and FAIL. Without a full check, printing just y[0] would have looked correct.

3. Make one thread do more. Launch SAXPY with a single block of 256 threads and change the kernel so each thread loops over elements i, i + 256, i + 512, …. Does the check still pass?

Solution
cuda
12345
__global__ void saxpy(int n, float a, const float *x, float *y) {
    for (int i = threadIdx.x; i < n; i += blockDim.x)
        y[i] = a * x[i] + y[i];
}
// launch: saxpy<<<1, 256>>>(n, 3.0f, x, y);

It passes, but it uses only one block, so only one of the GPU's SMs does any work. Chapter 2 generalizes this into the grid-stride loop, which uses every SM.

Check your understanding

Why is cudaDeviceSynchronize() needed before the CPU reads y in the SAXPY example?

The launch returns before the kernel finishes. Without waiting, the CPU could read y while the GPU is still writing it.

A program adds two 4 KB arrays once and copies the result back. Is it a good fit for the GPU?

No. The copies and launch overhead cost far more than the few thousand additions they enable. The CPU will be 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.

Practice These Concepts

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

Vector Additioneasy

Write a CUDA kernel that adds two arrays element-wise. Each thread should handle one element. The arrays are of size N = 1024.

Sign in to track your progress across challenges.