Kernels and launches
A kernel launch is a contract: this code, this many blocks, this many threads per block. This chapter fills in the contract and writes a kernel that actually touches memory.
Anatomy of a launch#
__global__ void kernel(float* data, int n) { // runs on the GPU, returns void
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) data[i] = 0.0f;
}
int main() {
dim3 grid(4, 3, 1); // 12 blocks
dim3 block(16, 16, 1); // 256 threads per block
kernel<<<grid, block>>>(d_data, n);
cudaDeviceSynchronize();
}The triple-chevron syntax takes either integers or dim3 values. Missing dimensions default to 1, so <<<4, 256>>> is <<<dim3(4,1,1), dim3(256,1,1)>>>.
| Limit | Value (all current GPUs) |
|---|---|
| Threads per block | 1,024 |
blockDim.x | 1,024 |
blockDim.y, blockDim.z | 1,024 each |
gridDim.x | 2³¹ − 1 blocks |
gridDim.y, gridDim.z | 65,535 blocks |
| Threads per warp | 32 |
Multi-dimensional shapes are a convenience for mapping threads onto data. They do not change performance; the hardware still linearises threads with x moving fastest. The threads chapter shows the 2D formulas.
A kernel that touches memory#
Our first real kernel scales every element of a one-million-element array. It uses managed memory so the example stays short; Moving data replaces this with explicit allocations and copies.
#include <cstdio>
#include <cuda_runtime.h>
__global__ void scale(float* data, int n, float factor) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
data[i] *= factor;
}
}
int main() {
const int n = 1000000;
float* data;
cudaMallocManaged(&data, n * sizeof(float));
for (int i = 0; i < n; ++i) data[i] = 1.0f;
int threads = 256;
int blocks = (n + threads - 1) / threads; // ceiling division
scale<<<blocks, threads>>>(data, n, 3.0f);
cudaDeviceSynchronize();
printf("n = %d, blocks = %d, threads = %d\n", n, blocks, threads);
printf("data[0] = %.1f\n", data[0]);
printf("data[%d] = %.1f\n", n - 1, data[n - 1]);
cudaFree(data);
return 0;
}n = 1000000, blocks = 3907, threads = 256 data[0] = 3.0 data[999999] = 3.0
Three details make this correct:
- Ceiling division — 1,000,000 does not divide by 256.
(n + threads - 1) / threadsrounds up, so the last block covers the tail. - Bounds check — the final block has more threads than remaining elements.
if (i < n)keeps extra threads from writing past the array. - The wait —
cudaDeviceSynchronize()ensures the kernel finished before the host readsdata.
Remove the bounds check and roughly 192 threads write beyond the array. Sometimes the program prints fine; sometimes it corrupts memory. That is the worst kind of bug.
Grid-stride loops#
Launching one thread per element is simple, but it wastes blocks when the array is small and overflows int when the array is huge. A grid-stride loop launches a fixed number of blocks and lets each thread process several elements:
__global__ void scale(float* data, int n, float factor) {
int stride = blockDim.x * gridDim.x;
for (int i = blockIdx.x * blockDim.x + threadIdx.x;
i < n;
i += stride) {
data[i] *= factor;
}
}With 1,024 blocks of 256 threads there are 262,144 threads. Thread 0 handles 0, 262144, 524288, ...; thread 1 handles 1, 262145, ...; and so on until every element is covered.
int threads = 256;
int blocks = 1024; // fixed, independent of n
scale<<<blocks, threads>>>(data, n, 3.0f);Why this is usually the better default:
- Works for any
n, including zero, without launching millions of blocks. - The grid size no longer changes when the input grows, so launch overhead is stable.
- Fewer blocks means less scheduling and index arithmetic per element.
- On small inputs it still fills the GPU because blocks are cheap.
The loop index is int above, which caps you at about 2.1 billion elements. For larger arrays use size_t or long long for i, n, and stride.
Launches are asynchronous#
The CPU does not wait for the GPU after <<<>>>. It queues the launch and runs the next line immediately:
printf("before launch\n");
scale<<<blocks, threads>>>(data, n, 3.0f);
printf("host is already on the next line\n");
cudaDeviceSynchronize();
printf("GPU finished, results are safe to read\n");That is a feature: the host can prepare the next buffer, launch another kernel, or copy data while the GPU works. It is also the source of the most common beginner bug — reading results before the kernel has run.
A kernel launch returns void, so you cannot check it directly. Check the launch configuration right after the launch, and check execution after a synchronisation:
scale<<<blocks, threads>>>(data, n, 3.0f);
cudaError_t err = cudaGetLastError();
if (err != cudaSuccess) {
fprintf(stderr, "launch: %s\n", cudaGetErrorString(err));
}
err = cudaDeviceSynchronize();
if (err != cudaSuccess) {
fprintf(stderr, "execution: %s\n", cudaGetErrorString(err));
}Wrap your checks once#
You will write this check after every CUDA call. Put it in a macro and stop thinking about it:
#pragma once
#include <cstdio>
#include <cstdlib>
#include <cuda_runtime.h>
#define CUDA_CHECK(call) \
do { \
cudaError_t err_ = (call); \
if (err_ != cudaSuccess) { \
std::fprintf(stderr, "%s:%d: %s\n -> %s\n", __FILE__, __LINE__, \
#call, cudaGetErrorString(err_)); \
std::exit(EXIT_FAILURE); \
} \
} while (0)CUDA_CHECK(cudaMalloc(&d_data, bytes));
scale<<<blocks, threads>>>(d_data, n, 3.0f);
CUDA_CHECK(cudaGetLastError()); // capture launch errors
CUDA_CHECK(cudaDeviceSynchronize()); // capture execution errorsDo not wrap the triple-chevron launch itself: it is not a function call and does not return an error code. cudaGetLastError() is the launch's error channel.
Put the pieces together#
Every kernel in the rest of the book follows this skeleton:
int main() {
// 1. allocate
float* d;
CUDA_CHECK(cudaMalloc(&d, n * sizeof(float)));
// 2. fill / copy input
CUDA_CHECK(cudaMemcpy(d, h, n * sizeof(float), cudaMemcpyHostToDevice));
// 3. choose a launch shape
int threads = 256;
int blocks = (n + threads - 1) / threads;
// 4. launch and check
kernel<<<blocks, threads>>>(d, n);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaDeviceSynchronize());
// 5. copy back, free
CUDA_CHECK(cudaMemcpy(h, d, n * sizeof(float), cudaMemcpyDeviceToHost));
CUDA_CHECK(cudaFree(d));
}Chapter 7 does step 1, 2, and 5 properly. The next chapter is about step 3: what those blocks and threads actually are, and how to index a matrix with them.
Exercises#
- Change
threadsto 128 and 512. Does the output change? Does the block count? - Rewrite
scalewith a grid-stride loop and launch exactly 64 blocks. Confirm the result is identical. - Remove
if (i < n)fromscale.cu. Compile with-lineinfoand run undercompute-sanitizer ./scale(orcuda-memcheckon older toolkits). What does it report? - Make
n = 0. What should happen? What does the launch do? - Time the kernel with
nvcc -O3vs-O0. Why is the difference smaller than you might expect for such a tiny kernel?