GPU by Example
2 / 16

Hello, GPU

6 min readChapter 2 of 16

Nine lines of CUDA. A compiler command. Eight threads running at once. That's the whole first step.

The smallest CUDA program#

hello.cuCUDA C++
#include <cstdio>

__global__ void hello() {
    printf("Hello from block %u, thread %u\n", blockIdx.x, threadIdx.x);
}

int main() {
    hello<<<2, 4>>>();
    cudaDeviceSynchronize();
    return 0;
}
Outputreference run
Hello from block 0, thread 0
Hello from block 0, thread 1
Hello from block 0, thread 2
Hello from block 0, thread 3
Hello from block 1, thread 0
Hello from block 1, thread 1
Hello from block 1, thread 2
Hello from block 1, thread 3

Two blocks, four threads each: eight invocations of hello(), all executing the same code with different built-in indices.

What each piece does#

  • __global__ marks a function as a kernel: it runs on the GPU and is called from host code. It must return void.
  • hello<<<2, 4>>>() is a kernel launch. The first number is the number of blocks in the grid; the second is the number of threads in each block. Read it as "2 blocks of 4 threads".
  • blockIdx.x and threadIdx.x are built-in variables. Every thread sees the same program but different values.
  • cudaDeviceSynchronize() blocks the host until the GPU has finished. Without it, main may return and kill the process before a single printf reaches the terminal.

Compile and run#

TerminalShell
$ nvcc -O3 hello.cu -o hello
$ ./hello
Hello from block 0, thread 0
...

nvcc is a compiler driver. It splits your .cu file into host code (compiled by your C++ compiler) and device code (compiled for the GPU), then links both into one executable.

FlagWhat it does
-O3Optimise host and device code
-arch=nativeTarget the GPU in this machine (or use -arch=sm_89, etc.)
-GDevice-side debug build (slow; use for cuda-gdb)
-lineinfoKeep source line info for the profiler
-Xcompiler -fPICPass a flag through to the host compiler
--ptxas-options=-vPrint register and shared-memory usage per kernel

Give every thread a unique job#

threadIdx only identifies a thread inside its block. To index a global array you combine all four built-ins:

id.cuCUDA C++
#include <cstdio>

__global__ void whoami() {
    int idx = blockIdx.x * blockDim.x + threadIdx.x;
    printf("block %u · thread %u · global index %d\n",
           blockIdx.x, threadIdx.x, idx);
}

int main() {
    whoami<<<4, 4>>>();
    cudaDeviceSynchronize();
    return 0;
}
Outputreference run
block 0 · thread 0 · global index 0
block 0 · thread 1 · global index 1
block 0 · thread 2 · global index 2
block 0 · thread 3 · global index 3
block 1 · thread 0 · global index 4
block 1 · thread 1 · global index 5
block 1 · thread 2 · global index 6
block 1 · thread 3 · global index 7
block 2 · thread 0 · global index 8
block 2 · thread 1 · global index 9
block 2 · thread 2 · global index 10
block 2 · thread 3 · global index 11
block 3 · thread 0 · global index 12
block 3 · thread 1 · global index 13
block 3 · thread 2 · global index 14
block 3 · thread 3 · global index 15

The formula

CUDA C++
int idx = blockIdx.x * blockDim.x + threadIdx.x;

is the most common line in CUDA. It linearises a two-level index space into one flat array index:

Output
blockIdx.x:   0        0        0        0        1        1   ...
threadIdx.x:  0  1  2  3  0  1  2  3  0  1  2  3  ...
blockDim.x:   4
idx:          0  1  2  3  4  5  6  7  8  9 10 11  ...

blockDim.x is the block size (4 here). Multiplying the block index by the block size skips over all the indices used by previous blocks.

When a launch is impossible#

Ask for 2,048 threads in one block and the launch fails. The hardware limit is 1,024 threads per block, and the runtime tells you at launch time:

oops.cuCUDA C++
#include <cstdio>

__global__ void k() {}

int main() {
    k<<<1, 2048>>>();
    cudaError_t err = cudaGetLastError();
    if (err != cudaSuccess) {
        printf("launch failed: %s\n", cudaGetErrorString(err));
    }
    return 0;
}
Outputreference run
launch failed: invalid configuration argument

cudaGetLastError() returns and clears the last error. Check it immediately after a launch. To wait for completion and surface execution errors (out-of-bounds access, illegal instruction), check the return value of cudaDeviceSynchronize() too:

CUDA C++
k<<<grid, block>>>();
cudaError_t err = cudaGetLastError();   // launch-time errors
if (err != cudaSuccess) { /* bad config, no memory, ... */ }

err = cudaDeviceSynchronize();         // execution-time errors
if (err != cudaSuccess) { /* illegal access, trap, ... */ }

We will wrap this in a CUDA_CHECK macro on the Moving data page. For now, remember there are two different failure points.

printf is a debugging tool, not an output channel#

Device printf is convenient for small examples, but it is not free:

  • Each thread's output is buffered in device memory and flushed when the buffer fills or the kernel ends.
  • The buffer is finite (about 1 MB by default). Overflow silently drops output.
  • Ordering between blocks is arbitrary; ordering within a thread is preserved.
  • A kernel that prints in a hot loop can be many times slower than the same kernel without printing.

For real work, write results to memory and inspect them on the host (or use a debugger/profiler). We do that from the next chapter onward.

Exercises#

  • Change the launch to hello<<<1, 8>>>(). How many lines print? Which built-in changes?
  • Print blockDim.x and gridDim.x from inside the kernel. Predict both values before running.
  • Delete cudaDeviceSynchronize(). Run the program a few times. Why is the output sometimes missing?
  • Launch whoami<<<2, 6>>>() and list the global indices. What is idx for block 1, thread 0?

Next: put those indices to work on real arrays, and learn why every launch needs a bounds check.