Hello, GPU
Nine lines of CUDA. A compiler command. Eight threads running at once. That's the whole first step.
The smallest CUDA program#
#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;
}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 returnvoid.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.xandthreadIdx.xare built-in variables. Every thread sees the same program but different values.cudaDeviceSynchronize()blocks the host until the GPU has finished. Without it,mainmay return and kill the process before a singleprintfreaches the terminal.
Compile and run#
$ 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.
| Flag | What it does |
|---|---|
-O3 | Optimise host and device code |
-arch=native | Target the GPU in this machine (or use -arch=sm_89, etc.) |
-G | Device-side debug build (slow; use for cuda-gdb) |
-lineinfo | Keep source line info for the profiler |
-Xcompiler -fPIC | Pass a flag through to the host compiler |
--ptxas-options=-v | Print 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:
#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;
}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
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:
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:
#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;
}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:
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.xandgridDim.xfrom 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 isidxfor block 1, thread 0?
Next: put those indices to work on real arrays, and learn why every launch needs a bounds check.