Write cuda layernorm kernel

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

Write cuda layernorm 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 LayerNorm (and RMSNorm) kernel, covering mean/variance computation strategies, Welford online accumulation, epsilon placeme

How to use this skill

Skill file

Skill: Write CUDA LayerNorm Kernel

Purpose

Guide the agent through designing and implementing a correct, efficient CUDA LayerNorm (and RMSNorm) kernel, covering mean/variance computation strategies, Welford online accumulation, epsilon placement, affine transform application, backward pass structure, and decomposition for non-power-of-two hidden dimensions.

Use this when

Do not use this when

Inputs the agent should gather first

Required reasoning process

  1. Determine the normalization work per row. Each row has D elements (the hidden dimension). A single row is normalized independently of all other rows. Assign one thread block (or one warp for small D) to each row. Grid size = number of rows = N * seq_len (or batch * seq if 3D input).
  1. Choose the accumulation strategy for mean and variance.

For production kernels: use Welford for its single-pass and numerical stability properties. For pedagogical or simple cases: two-pass is easier to verify.

  1. Design the warp+block reduction for Welford. Welford accumulators (count, mean, M2) must be merged at the warp and block level. Parallel Welford merge: given two accumulators (n_a, mean_a, M2_a) and (n_b, mean_b, M2_b), the combined accumulator is:

```

n = n_a + n_b

delta = mean_b - mean_a

mean = mean_a + delta * n_b / n

M2 = M2_a + M2_b + delta * delta * n_a * n_b / n

```

This merge is used at each step of the warp shuffle reduction and the smem block reduction. For simple sum reductions (two-pass approach), standard sum reductions suffice.

  1. Handle non-power-of-two D. The reduction pattern must correctly handle D values that are not multiples of the block size. Threads with index threadIdx.x + k * blockDim.x >= D must not read from global memory and must contribute the identity accumulator to the Welford merge.
  1. Compute the normalization. After the reduction:

```

mean = accumulated_sum / D (or from Welford directly)

var = M2 / D (from Welford, or second-pass sum-of-squared-deviations / D)

inv_std = rsqrtf(var + epsilon)

```

Each element is then normalized: y_i = (x_i - mean) * inv_std. For RMSNorm: skip mean computation; inv_std = rsqrtf(mean_of_squares + epsilon).

  1. Apply the affine transform. If gamma and beta are present: y_i = y_i * gamma[i] + beta[i]. The gamma and beta arrays have size D; each thread reads the gamma/beta value for its assigned position. These are typically loaded from global memory once per thread per call.
  1. Epsilon placement. Epsilon must be added inside the sqrt (i.e., rsqrtf(var + epsilon), not rsqrtf(var) + epsilon). The latter formula does not prevent division by zero and provides incorrect normalization when variance is near zero.
  1. Handle the backward pass (if required). The LayerNorm backward computes:

where x_hat_i = (x_i - mean) * inv_std is the normalized input.

The backward pass needs the normalized input x_hat or the saved mean and inv_std from the forward pass. Save those in the forward pass if backward is needed.

  1. Handle fp16/bf16 inputs. Convert fp16/bf16 inputs to fp32 immediately on load. All accumulation (sum, sum-of-squares, mean, variance) must be in fp32. Gamma and beta should be fp32 regardless of input dtype. The output is converted back to fp16/bf16 at the store step.

Kernel design rules

Correctness requirements

Performance requirements

Output format

The final response must include:

  1. Decomposition decision: rows-per-block assignment, thread block size, justification.
  2. Algorithm choice: Welford online or two-pass, with reasons.
  3. Kernel code: complete, compilable CUDA kernel for the forward pass. If backward is requested, a second kernel.
  4. Warp+block Welford reduction helper: device function implementing the parallel Welford merge.
  5. Host dispatch: grid/block dims, kernel call, saved tensor list for backward.
  6. Correctness notes: epsilon placement, fp16 accumulation strategy, boundary handling.
  7. RMSNorm variant (if requested): separate kernel or a compile-time template flag.
  8. Known limitations: maximum D for the chosen block size, non-divisible D behavior, backward pass numerical sensitivity.

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.