Write cuda softmax kernel

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

Write cuda softmax 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, numerically stable CUDA softmax kernel, covering online (single-pass) computation, row-parallel decomposition, warp-level reductions, fp16

How to use this skill

Skill file

Skill: Write CUDA Softmax Kernel

Purpose

Guide the agent through designing and implementing a correct, numerically stable CUDA softmax kernel, covering online (single-pass) computation, row-parallel decomposition, warp-level reductions, fp16/bf16 precision pitfalls, masked softmax variants, and when to fuse with attention versus implementing standalone.

Use this when

Do not use this when

Inputs the agent should gather first

Required reasoning process

  1. Choose the decomposition. Softmax is computed independently along each row of the softmax axis. Assign one row (or a small number of rows) to each thread block, or one row per warp if rows are short.
  1. Choose online (single-pass) vs two-pass formulation.

For most attention-scale softmax (seq_len <= 2048), the difference in memory reads is small. Online is more complex to implement; two-pass is easier to reason about correctness. Choose based on the bottleneck.

  1. Design the numerically stable formulation. Never compute exp(x) / sum(exp(x)) directly. Always subtract the row maximum first: exp(x - max) / sum(exp(x - max)). This prevents overflow in exp() for large x and prevents catastrophic cancellation in the denominator. The subtraction does not change the mathematical result but prevents floating-point exceptions.
  1. Design the warp-level max reduction. For the two-pass approach, each thread computes a local max over its assigned elements, then the warp performs a max reduction using __shfl_down_sync with fmaxf:

```

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

local_max = fmaxf(local_max, __shfl_down_sync(0xffffffff, local_max, offset));

```

Broadcast the warp max to all lanes: row_max = __shfl_sync(0xffffffff, local_max, 0);. If the block has multiple warps, store warp maxes to shared memory, sync, reduce the smem array in the first warp.

  1. Compute the shifted exponentials and sum. Each thread computes exp(x_i - row_max) for each element it owns. Sum these locally, then perform a warp+block reduction for the total sum (same pattern as step 4 but with addition).
  1. Normalize. Each thread divides its exp(x_i - row_max) by the total sum and writes to the output. This is a second pass over the elements. If using online softmax, this normalization is implicit in the update rule.
  1. Handle masked softmax. For additive masking (adding -inf or a large negative value to masked positions): apply the mask before the max computation. After subtracting max and computing exp, the masked positions contribute exp(-inf - max) = 0 to the sum. For boolean masks: convert to additive mask by mask ? 0.0f : -INFINITY before the exp computation. Special case: if all positions in a row are masked, the sum is 0 and division produces NaN. Decide how to handle this — common choices are: output 0, output 1/D (uniform), or output NaN (let the caller handle it). Document the choice.
  1. Handle fp16/bf16 inputs. For fp16 inputs: perform max reduction and exp-sum accumulation in fp32. Convert each fp16 element to fp32 before the subtraction and exp. The final output can be written as fp16 after division. Never compute hexp in fp16 with a direct exp(__half) in the warp reduction — fp16 has very limited dynamic range and exponents in [-87, 88] in fp32 translate to [-10, 10] in fp16 before saturation.
  1. Implement the backward pass if needed. The softmax backward computes dL/dx_i = softmax_i * (dL/dy_i - sum_j(softmax_j * dL/dy_j)). This requires the forward softmax output y and gradient dL/dy. The inner sum is a dot product reduction over the row, identical in structure to the forward pass. Reuse the same warp+block reduction pattern.

Kernel design rules

Correctness requirements

Performance requirements

Output format

The final response must include:

  1. Decomposition decision: rows-per-block assignment, justification based on row length and hardware.
  2. Algorithm choice: two-pass or online softmax, with explicit reasons.
  3. Kernel code: complete, compilable CUDA kernel. For masked softmax, include the mask handling path.
  4. Warp+block reduction helpers: reusable device functions for max-reduction and sum-reduction.
  5. Host dispatch: grid/block dimensions, smem size, kernel call.
  6. Numerical stability proof sketch: brief statement of why the max subtraction makes the computation stable.
  7. Known limitations: row lengths outside the tested range, NaN/inf input behavior, fully-masked row behavior.

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.