Write triton layernorm kernel

From tensormux/kernel-skills · View interactive version

Write triton layernorm kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a correct, numerically stable row-wise layer normalization kernel in Triton. This covers mean and variance computation with fp32 accumulation, epsilon handling, af

How to use this skill

Skill file

Skill: Write a Triton LayerNorm Kernel

Purpose

Guide the agent through implementing a correct, numerically stable row-wise layer normalization kernel in Triton. This covers mean and variance computation with fp32 accumulation, epsilon handling, affine transform with gamma/beta, the RMSNorm variant, masking for hidden dimensions not divisible by BLOCK_SIZE, and pointer arithmetic for 1D affine parameters applied to 2D or higher-rank inputs.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Input shape — (N, H) for 2D, or (B, T, H) for sequence inputs. Which dimension is normalized? (Assume last dimension H unless stated otherwise.)
  2. Hidden dimension H — fixed or dynamic? Is H a power of 2? Is H always divisible by BLOCK_SIZE?
  3. Input dtype — fp16, bf16, or fp32. Accumulation for mean and variance must be fp32.
  4. Affine transform — does the kernel apply learned gamma and beta parameters? Are they 1D tensors of shape (H,)?
  5. RMSNorm vs LayerNorm — LayerNorm subtracts mean and divides by std; RMSNorm skips mean subtraction and uses RMS of activations.
  6. Epsilon value — typically 1e-5 or 1e-6. Confirm whether it is added inside or outside the square root (both are used in practice — they differ numerically).
  7. Forward-only or training — if training, the mean and inverse-std (rstd) must be saved for the backward pass.
  8. Residual fusion — is there a residual to add before normalization (pre-norm pattern)?

Required reasoning process

  1. Assign one program per row. row_idx = tl.program_id(0). For a (B, T, H) input, the grid is (B * T,). Compute the row base pointer as input_ptr + row_idx * row_stride.
  1. Load the row in BLOCK_SIZE chunks with masking.

```python

col_offsets = tl.arange(0, BLOCK_SIZE)

mask = col_offsets < H

x = tl.load(x_ptr + row_idx * stride + col_offsets, mask=mask, other=0.0)

x = x.to(tl.float32)

```

Using other=0.0 is correct here (unlike softmax) because out-of-bounds positions should contribute 0 to the mean and sum-of-squares.

  1. Compute the mean (LayerNorm only). mean = tl.sum(x, axis=0) / H. Note: divide by H (the full row length), not by the number of loaded elements. If H is not a multiple of BLOCK_SIZE, the masked positions loaded as 0.0 do not affect the sum, and dividing by H is still correct.
  1. Subtract the mean (LayerNorm only). x_centered = x - mean. Apply the mask again to zero out positions beyond H.
  1. Compute the variance. var = tl.sum(x_centered * x_centered, axis=0) / H. For RMSNorm, skip mean subtraction: var = tl.sum(x * x, axis=0) / H.
  1. Compute rstd. rstd = 1.0 / tl.sqrt(var + epsilon).
  1. Normalize. x_norm = x_centered * rstd (or x * rstd for RMSNorm).
  1. Apply affine transform if gamma/beta are present.

```python

gamma = tl.load(gamma_ptr + col_offsets, mask=mask, other=1.0)

beta = tl.load(beta_ptr + col_offsets, mask=mask, other=0.0)

out = x_norm * gamma + beta

```

Gamma defaults to 1.0 and beta to 0.0 at out-of-bounds positions — these are identity values that produce no effect.

  1. Store the output.

```python

tl.store(out_ptr + row_idx * out_stride + col_offsets, out.to(output_dtype), mask=mask)

```

  1. If training, save mean and rstd. Store scalar mean and rstd to separate output buffers indexed by row_idx. These are needed in the backward pass.
  1. For H > BLOCK_SIZE, loop over chunks. This complicates the two-pass approach: pass 1 accumulates partial sums for mean and variance across all chunks, pass 2 normalizes and stores. Alternatively, use Welford's online algorithm to compute mean and variance in a single pass.

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through the following before finalizing:


Output format

The agent should produce:

  1. The Triton kernel function with @triton.jit, taking x_ptr, out_ptr, gamma_ptr, beta_ptr, mean_ptr (optional), rstd_ptr (optional), stride, H, epsilon, and BLOCK_SIZE: tl.constexpr as arguments.
  2. A Python launcher that computes the grid as (N_rows,), handles contiguity, extracts strides, and passes epsilon.
  3. RMSNorm variant (if requested) as a separate kernel or a conditional code path clearly marked.
  4. A correctness test comparing against torch.nn.LayerNorm with torch.allclose(atol=1e-4) for fp16 inputs and atol=1e-5 for fp32 inputs.
  5. Comment explaining epsilon placement convention used (inside vs outside sqrt).

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.