AoKO #4: The Pitfalls of Runtime Indices

Many kernels require a small amount of per-thread memory to act as a temporary buffer. If we know that we only need to store a few values, and know the maximum size at compile time, we can use a local array. In many cases, the compiler keeps this array in registers and thus they incur no performance overhead. But this isn’t always the case. Let’s look at a common pitfall.

This post is day 4 of Stream HPC’s Advent of Kernel Optimization, posting every weekday until the 25th of December. Check out all posts so far here.

A simple example

Consider the following kernel. Each thread loads a window of 64 consecutive elements from the input array, normalizes them so that they sum to one, and writes them to the output array. This kernel is deliberately very simple. The only notable bit is the handling of the tail, where the last thread might not have all 64 elements available.

constexpr int window_size = 64;
__global__ void normalize_chunks(const float* input, float* output, int N)
{
    const int tid = blockIdx.x * blockDim.x + threadIdx.x;

    // Small local buffer
    float buffer[window_size];

    // Determine how many items to read
    const int start = tid * window_size;
    const int end = min(start + window_size, N);
    const int items_to_read = end - start;

    // Read items into buffer
    float sum = 0.0f;
    for (int i = 0; i < items_to_read; ++i)
    {
        buffer[i] = input[start + i];
        sum += buffer[i];
    }

    // Write result
    const float scale = 1.0f / sum;
    for (int i = 0; i < items_to_read; ++i)
        output[start + i] = buffer[i] * scale;
}

At first glance, nothing looks wrong. But if we look at the generated SASS code (compiled with NVCC 13.1.0 for SM 89 using approximate float math for simpler assembly) we find the following in the inner loop for the loading section:

LDG.E R0, [R4.64] 
...
STL [R7], R0 
FADD.FTZ R3, R0, R3 
...

The LDG instruction loads our value from global memory, as expected. The FADD adds it to our sum accumulator (sum += buffer[i]). But the STL instruction means “store to local memory”. The word “local” here indicates the memory is local to this specific thread. But the memory is backed by slow DRAM, which is much slower than using registers. In practice our values are probably still loaded from L1 cache, but still that’s slower than keeping it in registers. Why is this?

Limitations of the instruction set

The key here is that GPU instruction sets generally cannot select a register with a dynamic index that is only known at runtime. The compiler must generate code that works for any value of the i variable. So it has to use memory that it can access using i as an offset, and thus it falls back to using local memory instead of registers.

Looking at our code, we as humans can clearly see that there’s an upper bound to the index. items_to_read can’t be larger than window_size, which is known at compile time. But the code is just convoluted enough that the compiler doesn’t recognize this. We can help the compiler a bit and simplify the calculation to:

const int items_to_read = min(window_size, N - start);

Now suddenly the compiler recognizes the upper bound and the STL instructions disappear! If we compile with the nvcc flag --resource-usage we can verify this even without looking at the assembly. Where the previous version printed it uses a “256 bytes stack frame”, our new version has 0 bytes and keeps the array in registers:

ptxas info    : Function properties for _Z16normalize_chunksPKfPfi
    0 bytes stack frame, 0 bytes spill stores, 0 bytes spill loads
ptxas info    : Used 72 registers, used 0 barriers, 372 bytes cmem[0]

With a known upper bound the compiler can fully unroll the loop. And as the loop is fully unrolled, each array index can be assigned a unique register. Consequently it does use significantly more registers (increased from 36 to 72), which in turn could also drastically lower occupancy. Whether this happens and what its impact on performance is would depend on many other factors in the kernel (e.g. shared memory usage, computational density, latency of memory operations, etc).

In our case this new version is about 8% faster than the original version (31.4 ms vs 34.0 ms, tested on 256M elements on my RTX 500 Ada laptop GPU).

Making it more robust

The lesson is that even an small, semantically equivalent change in the code can lead the compiler down a different code generation path. So if you want to know for sure what your kernel is doing, you have to check the generated assembly. Doing this for every loop that may or may not be unrolled can be tedious. A better approach is to write code that doesn’t rely on the compiler heuristics in the first place.

Instead of using runtime loop bounds, we can give the loops a compile-time upper bound and add a separate condition for the tail-handling. This applies to both loops. For our loading stage, we can write this as:

float sum = 0.0f;
for (int i = 0; i < window_size; ++i)
{
    if (i < items_to_read)
    {
        buffer[i] = input[start + i];
        sum += buffer[i];
    }
}

Now it is immediately clear that window_size is the upper bound for both loops and the compiler has the required information to fully unroll them. This also makes it run a tiny bit faster (about 0.2ms).

In this version indices are fully known at compilation time and the tail handling is made more explicit. The generated SASS code also shows that the instruction pipelining is improved. The previous version was unrolled, but still did an iterative approach of load -> add -> predicated branch:

// Repeated blocks of load -> accumulate -> branch

LDG.E R3, [R4.64]
FADD.FTZ R0, RZ, R3
@!P1 BRA `(.L_x_2)

LDG.E R7, [R4.64+0x4]
FADD.FTZ R0, R0, R7
@!P1 BRA `(.L_x_2)

LDG.E R9, [R4.64+0x8]
FADD.FTZ R0, R0, R9
@!P1 BRA `(.L_x_2)

But the latest version is better at pipelining the loads and adds. It also makes the loads and adds use predication instead of separate branch instructions.

// Load all values
@P6 LDG.E R66, [R2.64]
@P5 LDG.E R65, [R2.64+0x4]
@P4 LDG.E R64, [R2.64+0x8]
...
@P0 LDG.E R0, [R2.64+0xfc]

// Start accumulating
@P3 FADD.FTZ R69, RZ, R66
@P2 FADD.FTZ R69, R69, R65
@P1 FADD.FTZ R69, R69, R64
...

If you want to look at the full source and generated assembly for any of these versions, you can find them on Compiler Explorer.

Conclusion

Indexing a local array with indices known only at runtime can force the compiler to place it in slow local memory instead of registers. This can be fixed by helping the compiler determine all possible values for an index. Changing your loops to have a known iteration count is the most robust approach to do this, so that the generated assembly doesn’t depend on how clever the compiler’s analysis is.

Ready to Optimize?

Enhance Your Software Performance with Our Experts

Contact us today to discuss how Stream HPC can elevate your computing capabilities and lower costs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top