What the wavefront width actually costs you: porting a reduction kernel from CUDA to HIP on CDNA

There is a category of CUDA to HIP port that compiles cleanly, passes hipify-perl, runs without error, and still returns wrong numbers. I hit it on a block reduction and it took me a while to understand why, so here is the write-up.

The setup

A standard CUDA block reduction looks like this:

for (int offset = 16; offset > 0; offset /= 2)
    value += __shfl_down_sync(0xffffffff, value, offset);

That 16 is half of 32, which is the CUDA warp size. It is a hardcoded assumption baked into an enormous amount of production code, usually without a comment.

Why it breaks on CDNA

On AMD CDNA hardware (MI200, MI300) the wavefront is 64 lanes, not 32. On RDNA consumer cards it is 32, so the same code works there and you get a false sense of safety if you developed on an RX card and then moved to an Instinct part.

hipify-perl translates the shuffle correctly:

__shfl_down_sync becomes __shfl_down

But it does not touch the 16. So the loop starts at offset 16 and stops at 1, which means lanes 32-63 never participate in the tree. The kernel returns a value that is the sum of the first 32 lanes only. No error, no warning, no crash. Just a wrong answer that is exactly half of what you expect on uniform data, which is the kind of bug that survives code review because the number looks plausible.

The fix

The portable version reads the width from the architecture rather than assuming it:

for (int offset = warpSize / 2; offset > 0; offset /= 2)
    value += __shfl_down(value, offset);

warpSize is a compile-time constant in HIP and resolves to 64 on CDNA, 32 on RDNA. Same source, correct on both.

What I grep for now

After any hipify run I search for the magic numbers that encode warp assumptions:

grep -rn 'offset = 16\|offset = 32\|<< 5\|>> 5\|% 32\|/ 32' src/

The shift and modulo cases are the same bug in different clothes: lane_id % 32 silently aliases lanes 32-63 onto 0-31 on a 64-wide wavefront, and threadIdx.x >> 5 computes the wrong warp index.

A second one worth knowing

__ballot_sync and __activemask map to __ballot and __activemask, but the mask width changes meaning. On CDNA the ballot returns a 64-bit value. Any code that stores it in an unsigned int truncates the upper half of the wavefront without complaining.

Why this is worth writing down

The ROCm docs describe the mapping accurately, but the failure mode is quiet. Nothing in the toolchain tells you that a ported kernel is computing half the answer. The only defence is knowing that wavefront width is the one architectural difference that changes results rather than just performance.

If anyone has hit other silent-correctness cases in HIP porting I would be interested — the performance differences are well documented, the correctness ones much less so.