Write cuda reduction kernel

From wenyi-li/awesome-agent-kernel-skills · View interactive version

Write cuda reduction kernel is an AI agent skill from the GitHub repository wenyi-li/awesome-agent-kernel-skills. Guide the agent through designing and implementing a correct, efficient CUDA reduction kernel for a given operator (sum, max, min, or custom binary associative op), covering warp-level primitives, blo

How to use this skill

Skill file

Skill: Write CUDA Reduction Kernel

Purpose

Guide the agent through designing and implementing a correct, efficient CUDA reduction kernel for a given operator (sum, max, min, or custom binary associative op), covering warp-level primitives, block-level reduction, multi-block strategies, and when to use CUB instead.

Use this when

Do not use this when

Inputs the agent should gather first

Required reasoning process

  1. Choose single-pass vs two-pass strategy. A single block can reduce up to blockDim.x elements in one pass. For inputs larger than one block, two strategies exist:
  1. Design the warp-level reduction. Use __shfl_down_sync for all warp-level reductions. The standard pattern reduces 32 lanes to 1:

```

for (int offset = 16; offset > 0; offset >>= 1)

val = op(val, __shfl_down_sync(0xffffffff, val, offset));

```

The mask 0xffffffff is correct only when all 32 lanes in the warp are active. If the thread count is not a multiple of 32 (partial warp at the tail of the input), use a mask that includes only the active lanes: compute it as __ballot_sync(0xffffffff, thread_is_active) or predicate the loop.

  1. Design the block-level reduction. After warp reduction, each warp has a partial result in lane 0. Collect these into shared memory (one value per warp, so blockDim.x / 32 values), sync, then reduce that small array using the first warp. Total smem needed: (blockDim.x / 32) * sizeof(dtype).
  1. Handle the batched / axis reduction case. For a [B, L] tensor reduced along axis=1 to [B]:
  1. Handle strided inputs. If the input is not contiguous, compute the correct flat index using stride values. Ensure that the global memory access pattern is coalesced: ideally, threads with consecutive threadIdx.x access consecutive memory addresses. For axis=1 reductions on row-major tensors, consecutive threads access consecutive elements in the same row — this is coalesced. For axis=0 reductions on row-major tensors, consecutive threads access elements in different rows — this is strided and will underperform; consider transposing first or restructuring the access.
  1. Choose the accumulator type. For fp16 or bf16 inputs with a sum reduction, always accumulate in fp32 unless the application has explicitly verified that fp16 accumulation does not cause unacceptable numerical error. The per-element conversion __half2float adds negligible cost compared to memory bandwidth.
  1. Implement the multi-block partial result strategy. If using two-pass: allocate a temporary buffer of size ceil(N / blockDim.x) values. First kernel: each block reduces its chunk and writes its partial to partials[blockIdx.x]. Second kernel: launched with a single block (or a few blocks), reduces partials to the final output. Ensure the partial buffer dtype matches the accumulator dtype, not the input dtype.
  1. Handle non-power-of-two block sizes and input sizes. The warp reduction pattern with __shfl_down_sync works for any thread count if the mask is set correctly. The block-level smem stage works for any block size that is a multiple of 32. For non-multiple-of-32 block sizes, the final warp may have fewer than 32 active threads — mask those correctly.

Kernel design rules

Correctness requirements

Performance requirements

Output format

The final response must include:

  1. Strategy decision: single-pass or two-pass, with justification based on input size and operator properties.
  2. Kernel code: complete, compilable CUDA kernel(s). If two-pass, both kernels plus the host dispatch function.
  3. Warp reduction helper: a device function for the warp-level reduction with explicit mask and operator.
  4. Block reduction helper: a device function for the block-level reduction using shared memory.
  5. Host dispatch: kernel launch parameters (block size, grid size), temporary buffer allocation if needed, kernel calls in the correct order.
  6. Correctness notes: explicit statement of identity element used, boundary handling strategy, warp mask rationale.
  7. Numerical precision notes: accumulator dtype, any loss of precision relative to full fp64 reference.
  8. Known limitations: cases where this kernel will produce non-deterministic results or underperform.

Common failure modes

Review checklist

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.