Skip to content
systemcoding.dev
GPU

Tune Block Size With cudaOccupancyMaxPotentialBlockSize

Ask the CUDA runtime for a block size that maximizes theoretical occupancy with cudaOccupancyMaxPotentialBlockSize, and learn why you must still time it.

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

Choosing a block size of 256 by habit works for many kernels and is wrong for some. The best value depends on how many registers the compiled kernel uses, how much shared memory it needs and what the GPU's limits are, and those change with every compiler release and every architecture. The runtime can do the arithmetic for you. cudaOccupancyMaxPotentialBlockSize takes a kernel and returns the block size that gives the highest theoretical occupancy, plus the smallest grid that fills the device. This post shows how to call it in CUDA 12.9, how to handle shared memory that depends on block size, how to read the companion call, cudaOccupancyMaxActiveBlocksPerMultiprocessor, and why the answer is a starting point and not a verdict. The resource numbers it uses are the ones from the nvcc resource usage post.

What the function computes

Occupancy is the number of resident warps per multiprocessor divided by the maximum. For a given kernel, each candidate block size produces a different count of blocks that fit, limited by registers, shared memory, the maximum threads per multiprocessor and the maximum blocks per multiprocessor. The function evaluates the candidates, using the kernel's actual register and shared memory use read from the compiled code, and returns the block size with the highest occupancy. Among ties it prefers the larger block size, which is a documented behavior of the C++ version in cuda_runtime.h.

The signature in the runtime API is:

cpp
cudaError_t cudaOccupancyMaxPotentialBlockSize(
    int *minGridSize, int *blockSize, T func,
    size_t dynamicSMemSize = 0, int blockSizeLimit = 0);

minGridSize receives the minimum grid size needed to reach full occupancy across the device, blockSize receives the block size, func is the kernel, dynamicSMemSize is the dynamic shared memory per block in bytes and blockSizeLimit caps the answer, with 0 meaning no cap.

A complete use

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

__global__ void scaleAdd(const float *x, float *y, float a, int n)
{
    int i = blockIdx.x * blockDim.x + threadIdx.x;
    if (i < n) y[i] = a * x[i] + y[i];
}

int main()
{
    const int n = 1 << 22;
    float *x, *y;
    cudaMalloc(&x, n * sizeof(float));
    cudaMalloc(&y, n * sizeof(float));
    cudaMemset(x, 0, n * sizeof(float));
    cudaMemset(y, 0, n * sizeof(float));

    int minGrid = 0, block = 0;
    cudaOccupancyMaxPotentialBlockSize(&minGrid, &block, scaleAdd, 0, 0);
    int grid = (n + block - 1) / block;

    printf("block=%d minGrid=%d grid=%d\n", block, minGrid, grid);
    scaleAdd<<<grid, block>>>(x, y, 2.0f, n);
    cudaDeviceSynchronize();

    cudaFree(x); cudaFree(y);
    return 0;
}
Text
block=1024 minGrid=82 grid=4096

The numbers depend on the GPU and the compiler, so yours will differ. For this example, on a device with 82 multiprocessors, a kernel using few registers fits one block of 1,024 threads per multiprocessor up to the thread limit. The minGrid value of 82 is a lower bound for full occupancy on this device, and the grid for the data, 4,096 blocks, is far larger, so the whole device stays busy. If your grid were smaller than minGrid, some multiprocessors would sit idle, which means your problem is too small for the device.

Note that the function returns a block size, not a grid size. You compute the grid from your data, as in the launch configuration post.

When shared memory depends on block size

A kernel that allocates one float of shared memory per thread has a footprint that grows with the block. A fixed dynamicSMemSize cannot express that. Use the variable form, which takes a function from block size to bytes:

cpp
int perThreadBytes(int blockSize) { return blockSize * sizeof(float); }

int minGrid, block;
cudaOccupancyMaxPotentialBlockSizeVariableSMem(
    &minGrid, &block, tiledKernel, perThreadBytes, 0);

The callable is invoked for each candidate block size, and the result is the largest block size that fits. Without it, a block size computed for zero shared memory may fail at launch, because the dynamic allocation you pass later pushes it over the limit. For static __shared__ arrays the compiler already counted them, so the simple call is enough.

The companion call: how many blocks fit?

Sometimes you already have a block size and want the occupancy it produces. cudaOccupancyMaxActiveBlocksPerMultiprocessor returns the number of blocks per multiprocessor:

cpp
int blocksPerSm = 0;
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&blocksPerSm, scaleAdd, 256, 0);

cudaDeviceProp p;
cudaGetDeviceProperties(&p, 0);
float occ = (blocksPerSm * 256.0f) / p.maxThreadsPerMultiProcessor;
printf("blocks/SM=%d occupancy=%.2f\n", blocksPerSm, occ);
Text
blocks/SM=6 occupancy=1.00

On a multiprocessor limited to 1,536 resident threads, six blocks of 256 reach all 1,536, an occupancy of 1.00. The printed values are an example of the arithmetic. Use this call to compare candidate block sizes you care about, such as 128, 256 and 512, in one loop.

Why the answer is not final

The function maximizes theoretical occupancy, and that is not the same as speed. Three reasons make it a starting point.

First, occupancy only matters while latency is the bottleneck. A kernel limited by memory bandwidth reaches the same speed at 50 percent occupancy as at 100, and the largest block size may even hurt through scheduling granularity or cache pressure. Second, the best block shape for a two-dimensional kernel is not a single number. You need to decide the x and y split, and the calculator returns a total thread count, which you then arrange, keeping x a multiple of 32 so loads coalesce. Third, kernels that rely on shared memory tiles or a specific block shape, such as a 16 by 16 tile in the matrix multiply, fix the block size by algorithm and ignore the calculator.

The right use is to get a good value without guessing, then time two or three neighbors:

cpp
int candidates[] = {128, 256, 512, block};
for (int c : candidates) {
    cudaEvent_t t0, t1;
    cudaEventCreate(&t0); cudaEventCreate(&t1);
    cudaEventRecord(t0);
    scaleAdd<<<(n + c - 1) / c, c>>>(x, y, 2.0f, n);
    cudaEventRecord(t1);
    cudaEventSynchronize(t1);
    float ms; cudaEventElapsedTime(&ms, t0, t1);
    printf("block=%4d  %.3f ms\n", c, ms);
}

The output is a table of times that depends on the device. If every candidate lands within noise of the others, the kernel is insensitive to block size, and 256 is as good as any. If one is clearly faster, use it.

Use the result as a launch default, not a constant

Compute the block size once at start-up per kernel and device, store it and reuse it. Do not hard-code the number you see on your development GPU into a shipped program, since the best value changes across architectures. The call is cheap, so calling it per device during initialization costs nothing.

Limits and error cases

If the kernel uses more registers than any block can have, the function returns a block size of 0 or an error, which means the kernel cannot launch at all at any size, a case worth checking before the launch fails with too many resources requested for launch. It also does not know about cooperative launches or clusters, which impose their own grid size limits and have their own occupancy calls, such as cudaOccupancyMaxActiveClusters. Check the return value like any runtime call.

Tuning two-dimensional blocks

The calculator returns a total thread count. For a two-dimensional kernel you still choose the shape. Keep x a multiple of 32 so that a warp's loads coalesce along rows, and spend the rest of the product on y. If the calculator suggests 512 threads, dim3(32, 16) is a sound arrangement, and dim3(16, 32) is a poor one because each warp then spans two rows of 16 elements and loses coalescing at the row break:

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

Here block1d is the value returned by the calculator, 512 in the example, giving 32 by 16. When the tile is part of the algorithm, such as the 32 by 32 transpose tile in the performance guide, the shape is fixed and you should use the calculator only to see what occupancy it yields, and to decide whether a smaller tile with more work per thread is worth testing.

Querying at start-up for several kernels

A program with ten kernels needs ten answers. Wrap the query in a small helper that returns a launch plan for a kernel and an element count, so launch sites stay clean:

cpp
struct Plan { int grid; int block; };

template <typename K>
Plan planFor(K kernel, size_t n, size_t dynSmem = 0)
{
    int minGrid = 0, block = 0;
    cudaOccupancyMaxPotentialBlockSize(&minGrid, &block, kernel, dynSmem, 0);
    return { (int)((n + block - 1) / block), block };
}

// usage:
// Plan p = planFor(scaleAdd, n);
// scaleAdd<<<p.grid, p.block>>>(x, y, 2.0f, n);

The helper is a template over the kernel type so it works with any signature, and it computes the grid from the problem size in one place, which removes the class of mistakes where the grid and block drift apart. Cache the plan if the same kernel runs many times with the same size, since the occupancy query itself is cheap but not free.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.