Skip to content
systemcoding.dev
GPU

Pick Grid and Block Dimensions for a CUDA Kernel From Your Data Size

Compute the CUDA grid size with ceiling division, choose a block size that is a multiple of 32, and guard the tail so no thread reads past the end of the array.

7 min read
Summarize in AI
Flat illustration of a GPU die of compute units with one thread block lit, with the NVIDIA, C and Khronos Group logos.

Every CUDA kernel launch needs two numbers before it does any work: how many threads sit in a block, and how many blocks sit in the grid. Pick them badly and the kernel either skips the last elements of your array or reads past its end. This post shows the arithmetic that turns an element count into a launch configuration, using CUDA 12.9 and plain C-style host code. It is the first rung of the GPU ladder, so every term is defined as it appears, and it assumes you have already seen a "hello world" kernel from the CUDA programming guide.

What a grid, a block and a thread are

A kernel launch creates a grid of thread blocks. Each block holds a number of threads. Inside the kernel, three built-in variables tell a thread where it is: threadIdx.x is its index inside its block, blockIdx.x is the index of its block inside the grid, and blockDim.x is the number of threads per block. The programming guide defines these as dim3-style values, and the .x suffix means we are using the first of up to three dimensions. One dimension is enough for a flat array.

The global index of a thread in a one-dimensional launch is therefore:

cpp
int i = blockIdx.x * blockDim.x + threadIdx.x;

Block 0 covers indices 0 to blockDim.x - 1, block 1 covers the next blockDim.x indices, and so on. If your array has n elements, you want at least n threads in total, and each thread handles the element whose index equals its global index.

Choose the block size first

The hardware runs threads in groups of 32 called warps, so the block size should be a multiple of 32. A block of 100 threads still occupies four warps and wastes 28 lanes in the last one. The programming guide gives the limit: a block may hold at most 1,024 threads on every GPU generation that CUDA 12.9 supports.

A good default for a simple element-wise kernel is 256. It is a multiple of 32, it is far from the 1,024 cap, and it leaves room for several blocks to share one streaming multiprocessor. Later posts on this site cover how to tune the number with the occupancy API. For now, treat 128, 256 and 512 as sensible starting values and change them only when a profiler tells you to.

Compute the grid size with ceiling division

Integer division rounds down, so n / blockSize loses the remainder. If n is 1,000 and the block size is 256, 1000 / 256 is 3, which gives 768 threads and leaves 232 elements untouched. The fix is a ceiling division:

cpp
int blockSize = 256;
int gridSize = (n + blockSize - 1) / blockSize;

With n = 1000, that is (1000 + 255) / 256, which is 1255 / 256, which is 4. Four blocks of 256 threads give 1,024 threads for 1,000 elements. For an n that is an exact multiple of the block size, such as 1,024, the formula still returns 4 and wastes nothing.

Guard the tail inside the kernel

Ceiling division launches more threads than elements, so the extra threads must do nothing. That is what the bounds check is for:

scale.cucpp
#include <cstdio>
#include <cuda_runtime.h>

__global__ void scale(float *data, float factor, int n)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) {
        data[i] *= factor;
    }
}

int main()
{
    const int n = 1000;
    float *d_data = nullptr;
    cudaMalloc(&d_data, n * sizeof(float));
    cudaMemset(d_data, 0, n * sizeof(float));

    int blockSize = 256;
    int gridSize = (n + blockSize - 1) / blockSize;
    scale<<<gridSize, blockSize>>>(d_data, 2.0f, n);
    cudaError_t err = cudaDeviceSynchronize();

    printf("grid=%d block=%d threads=%d elements=%d status=%s\n",
           gridSize, blockSize, gridSize * blockSize, n,
           cudaGetErrorString(err));
    cudaFree(d_data);
    return 0;
}
Text
grid=4 block=256 threads=1024 elements=1000 status=no error

The 24 surplus threads in block 3 compute i values of 1,000 to 1,023, fail the i < n test and return. Remove the test and those 24 threads write 96 bytes past the end of the allocation, which is the classic source of the error described in our post on fixing "an illegal memory access was encountered".

Use dim3 when the data is two-dimensional

An image or a matrix maps better to a two-dimensional launch. dim3 holds up to three values, and any you leave out default to 1:

cpp
dim3 block(16, 16);
dim3 grid((width + block.x - 1) / block.x,
          (height + block.y - 1) / block.y);

A 16 by 16 block is still 256 threads, so it respects the multiple-of-32 rule. The guide limits the product of the block dimensions to 1,024, and the x and y limits individually. Inside the kernel you compute col from x and row from y, and guard both:

cpp
int col = blockIdx.x * blockDim.x + threadIdx.x;
int row = blockIdx.y * blockDim.y + threadIdx.y;
if (col < width && row < height) {
    out[row * width + col] = in[row * width + col] * 0.5f;
}

Keep x as the fast-moving index in memory. Threads with consecutive threadIdx.x then touch consecutive addresses, which matters for performance and is the subject of the coalescing post later in this cluster.

A grid-stride loop when the data is huge or the grid is capped

The x dimension of a grid can hold up to 2,147,483,647 blocks on current hardware, so a single launch covers any array that fits in GPU memory. Even so, many kernels are written with a grid-stride loop, which decouples the launch size from the data size:

cpp
__global__ void scaleStride(float *data, float factor, int n)
{
    int stride = blockDim.x * gridDim.x;
    for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < n; i += stride) {
        data[i] *= factor;
    }
}

Now any launch configuration is correct, because each thread keeps stepping by the total thread count until it passes n. You can launch a grid sized to the device instead of the data, which makes the kernel easy to reuse and easy to debug with a one-block launch. The cost is a loop and a little more index arithmetic, which is irrelevant for memory-bound kernels.

Check the launch itself

A launch with a bad configuration does not stop the program. A block size of 2,048 fails with invalid configuration argument, and you will only see it if you ask:

cpp
scale<<<gridSize, 2048>>>(d_data, 2.0f, n);
cudaError_t err = cudaGetLastError();
printf("%s\n", cudaGetErrorString(err));
Text
invalid configuration argument

Call cudaGetLastError() right after the launch to catch configuration errors, and cudaDeviceSynchronize() to catch errors that happen while the kernel runs.

Who this does not fit

The ceiling-division recipe suits kernels where one thread owns one element. Reductions, stencils and tiled matrix kernels pick the block size from a shared memory tile or an algorithm, and they size the grid from the number of tiles. In those cases start from the algorithm and let the data size decide only how many blocks you need.

Why not one giant block or one thread per block

Two extremes show why the split matters. A single block of 1,024 threads can cover only 1,024 elements per launch, and it runs on one streaming multiprocessor while the rest of the GPU sits idle. A launch of n blocks with one thread each is legal, but every block then occupies a warp slot while using one lane out of 32, so you pay for 32 lanes and use one. The useful region is in between: enough blocks to keep every multiprocessor busy, and enough threads per block to fill whole warps.

A quick way to reason about it is to count blocks. A GPU with 80 multiprocessors needs at least 80 blocks to touch every one of them, and usually several times that so a late block can take over when an early one finishes. Your element-wise kernel over a million floats launches 3,907 blocks of 256 threads, which is plenty. A kernel over 2,000 floats launches 8 blocks and leaves most of a large GPU unused no matter how you tune the block size, which is a hint that the problem is too small for the device and the launch overhead will dominate.

When a result looks wrong, print the configuration before you suspect the kernel. A tiny helper keeps the arithmetic in one place and makes it testable on the host:

cpp
inline int ceilDiv(int n, int d) { return (n + d - 1) / d; }

int blocksFor(int n, int blockSize) { return ceilDiv(n, blockSize); }

Calling blocksFor(1000, 256) returns 4, blocksFor(1024, 256) returns 4 and blocksFor(1025, 256) returns 5. Those three values are the boundary cases worth checking by hand, because off-by-one mistakes hide exactly there. A good habit is to run your kernel on n values of 1, 255, 256, 257 and a prime such as 1,009, and compare each against a plain CPU loop. If the guard or the grid formula is wrong, one of those sizes will expose it while a round number like 1,024 will not.

A related mistake is passing n as size_t and computing the grid in int. For arrays beyond two billion elements the index arithmetic overflows int, and the fix is a 64-bit index in the kernel and a grid-stride loop. You will rarely hit it on a first project, but it is worth knowing why large-array kernels use size_t everywhere.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.