Write triton rmsnorm kernel

From tensormux/kernel-skills · View interactive version

Write triton rmsnorm kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a correct, numerically stable RMSNorm kernel in Triton: `y = x * rsqrt(mean(x², axis=-1) + eps) * weight`. RMSNorm is the dominant normalization in modern decoder-

How to use this skill

Skill file

Skill: Write a Triton RMSNorm Kernel

Purpose

Guide the agent through implementing a correct, numerically stable RMSNorm kernel in Triton: y = x * rsqrt(mean(x², axis=-1) + eps) * weight. RMSNorm is the dominant normalization in modern decoder-only LLMs (LLaMA, Mistral, Qwen, Gemma, DeepSeek). This skill covers one-pass sum-of-squares with fp32 accumulation, the persistent kernel pattern when the hidden dim fits in a single tile, masking for non-divisible tails, the affine weight broadcast (no bias), and the backward pass. RMSNorm is structurally simpler than LayerNorm — no mean subtraction, no Welford — but the failure modes around fp16 squaring and weight pointer arithmetic still bite.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Input shape — usually (B, T, H) or (N, H). Confirm H is the trailing dimension and the tensor is contiguous along H.
  2. Hidden dimension H — fixed (e.g., 4096 for LLaMA-7B, 8192 for LLaMA-70B, 6144 for Qwen) or dynamic? Multiple of 128? Does it fit in a reasonable BLOCK_SIZE (≤ 8192)?
  3. Input dtype — fp16, bf16, or fp32. fp16 squaring overflows around |x| ≈ 256; bf16 squaring underflows easily for small activations. Accumulation must be fp32 regardless.
  4. Weight presence and dtype — RMSNorm has a per-feature weight of shape (H,). Confirm dtype (often the activation dtype in LLaMA, sometimes fp32). There is no bias.
  5. Epsilon value — typically 1e-5 (LLaMA, Mistral) or 1e-6 (Gemma). Placement is rsqrt(mean_sq + eps) (inside the sqrt). rsqrt(mean_sq) + eps is wrong and not a real convention.
  6. Forward-only or forward + backward — if backward is needed, save rrms = rsqrt(mean_sq + eps) per row.
  7. Residual fusion — does the kernel read a residual and add it before squaring? If yes, must the post-add value also be written back as the next block's residual stream?
  8. Target architecture — NVIDIA SM75/80/90/100 or AMD CDNA2/3. BLOCK_SIZE and num_warps choices differ; on CDNA prefer num_warps=4 or 8 and avoid tensor-core-specific assumptions.

Required reasoning process

  1. Assign one program per row. row_idx = tl.program_id(0). For (B, T, H), flatten to (B*T, H) and launch grid (B*T,). Row base pointer is x_ptr + row_idx * row_stride.
  1. Decide one-pass vs two-pass. RMSNorm only needs Σ x², no mean-then-variance dance. One pass is always sufficient when H ≤ BLOCK_SIZE. No Welford needed. For H > BLOCK_SIZE, loop the row in chunks accumulating Σ x² into a fp32 scalar, then loop a second time to apply the scale.
  1. Persistent (single-block) pattern when H fits. For LLM-class hidden sizes (4096, 5120, 6144, 8192), set BLOCK_SIZE = next_power_of_2(H) and load the full row in one tile. The row stays in registers between the reduction and the scale step — no second HBM read.
  1. Load the row in fp32 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_f32 = x.to(tl.float32)

```

other=0.0 is correct: out-of-bounds positions contribute 0 to the sum-of-squares.

  1. Compute mean of squares in fp32. mean_sq = tl.sum(x_f32 * x_f32, axis=0) / H. The denominator is H (the full row length), not the count of valid lanes — masked-as-zero lanes correctly contribute 0.
  1. Compute reciprocal RMS. rrms = 1.0 / tl.sqrt(mean_sq + eps) or equivalently tl.rsqrt(mean_sq + eps). rsqrt typically lowers to a single hardware instruction (rsqrt.approx.f32 on NVIDIA). Eps must be inside the sqrt.
  1. Load the per-feature weight (1D, shape (H,)). w = tl.load(weight_ptr + col_offsets, mask=mask, other=0.0). The pointer is offset only by col_offsets — no row index. The weight broadcasts across all rows.
  1. Apply normalization and weight. y = x_f32 * rrms; y = y * w.to(tl.float32). Algebraic refactorings ((x * w) * rrms, etc.) are valid in exact arithmetic but reorder rounding — pick one and stay consistent with the saved-stat convention.
  1. Store the output with the same mask. tl.store(y_ptr + row_idx * out_stride + col_offsets, y.to(output_dtype), mask=mask).
  1. If training, save rrms. Write the scalar rrms to a (N_rows,) buffer at index row_idx. The backward kernel reads this. Do not save mean_sq or rms — that forces an extra op in the backward.
  1. For H > BLOCK_SIZE, two-pass loop. Pass 1: accumulate acc += tl.sum(x_chunk * x_chunk) in fp32 across chunks, then rrms = rsqrt(acc / H + eps). Pass 2: re-load each chunk, multiply by rrms and the corresponding weight chunk, store. Costs one extra HBM read per row; prefer the persistent pattern whenever it fits.
  1. Backward pass formulation. Given upstream dy, with x_normed = x * rrms:

Kernel design rules


Correctness requirements


Performance requirements

The agent must reason through the following before finalizing:


Output format

The agent should produce:

  1. The forward Triton kernel with @triton.jit, taking x_ptr, y_ptr, weight_ptr, rrms_ptr (optional, for training), row_stride, out_stride, H, eps, and BLOCK_SIZE: tl.constexpr.
  2. Backward kernel(s) if requested — one for dx (per-row, mirrors the forward decomposition) and one for dweight (per-feature reduction across the batch).
  3. A Python wrapper that flattens leading dims to (N_rows, H), checks contiguity along H, computes the grid as (N_rows,), picks BLOCK_SIZE as the smallest power of 2 ≥ H (with a fallback to the two-pass kernel above the chosen cap), and exposes a torch.autograd.Function if training is needed.
  4. A correctness test comparing against:

```python

ref = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + eps) * weight

```

with torch.allclose(atol=1e-3, rtol=1e-3) for fp16, atol=1e-2, rtol=1e-2 for bf16, atol=1e-5 for fp32. Include at least one H not divisible by BLOCK_SIZE (e.g., H = 4097) to exercise the mask path.

  1. A short comment block stating: dtype assumptions, eps convention (inside sqrt), weight shape (H,), absence of bias, and the saved-statistics convention (rrms not rms) if backward is supported.

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.