Write triton fused add rmsnorm kernel

From tensormux/kernel-skills · View interactive version

Write triton fused add rmsnorm kernel is an AI agent skill from the GitHub repository tensormux/kernel-skills. Guide the agent through implementing a single Triton kernel that computes `y = rmsnorm(x + residual)` while also writing back `x + residual` for the next transformer block's residual stream. This fusi

How to use this skill

Skill file

Skill: Write a Triton Fused Add+RMSNorm Kernel

Purpose

Guide the agent through implementing a single Triton kernel that computes y = rmsnorm(x + residual) while also writing back x + residual for the next transformer block's residual stream. This fusion is the dominant pattern in LLaMA, Mistral, Qwen, and similar decoder blocks: every attention sub-block and every MLP sub-block ends with residual_add -> rmsnorm. Done correctly, the kernel saves one full read+write pass over the activation tensor compared to a naive add kernel followed by an rmsnorm kernel, and removes one launch.


Use this when


Do not use this when


Inputs the agent should gather first

Before writing any code, confirm:

  1. Input dtype — fp16, bf16, or fp32 for x and residual. Both should match. The summed residual write-back keeps the input dtype; the normalized y typically keeps the same dtype as well.
  2. Hidden dimension H — fixed or dynamic? Power of 2? Always divisible by BLOCK_SIZE? Does it fit in a single BLOCK_SIZE (single-pass) or require a loop (two-pass)?
  3. Batch shape — (N, H), (B, T, H), or higher rank. Confirm normalization is over the last dimension only.
  4. Epsilon — typically 1e-5 or 1e-6. Confirm placement (inside vs outside sqrt); PyTorch RMSNorm convention is inside.
  5. Weight (gamma) dtype — most checkpoints store gamma in fp16/bf16. Multiply in fp32 then cast back.
  6. In-place vs out-of-place residual write — does the caller want x overwritten with x + residual, or written to a separate output buffer? Aliasing rules matter.
  7. Backward needed? — if yes, you must save rstd and the summed activation, and design a backward that splits the gradient into the residual path and the rmsnorm path.
  8. Eps double-counting — confirm the downstream kernel (e.g., the next block's QKV) does not also add eps if it consumes the rstd you produce.

Required reasoning process

  1. Assign one program per row. row_idx = tl.program_id(0). Grid is (N_rows,) where N_rows = prod(batch_dims). Compute the row base pointer as x_ptr + row_idx * row_stride and similarly for residual_ptr, y_ptr, and the summed-output pointer.
  1. Load x and residual together with a mask.

```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)

res = tl.load(res_ptr + row_idx * stride + col_offsets, mask=mask, other=0.0)

```

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

  1. Cast to fp32 and compute the sum.

```python

x = x.to(tl.float32)

res = res.to(tl.float32)

h = x + res

```

This is the single most important precision choice. Residual streams in deep transformers grow over 32+ layers; performing the add in fp16/bf16 loses bits before the squaring step and corrupts the variance estimate.

  1. Write the summed residual back immediately.

```python

tl.store(sum_ptr + row_idx * stride + col_offsets, h.to(input_dtype), mask=mask)

```

Cast back to the input dtype on the way out. This is the value the next block consumes as its residual; it is not optional and must be written in the same kernel pass to realize the fusion benefit.

  1. Compute the mean square in fp32.

```python

var = tl.sum(h * h, axis=0) / H

rstd = 1.0 / tl.sqrt(var + eps)

```

Divide by H, not by the count of unmasked elements. Out-of-bounds positions loaded as 0.0 contribute 0 to the sum-of-squares; dividing by H is correct.

  1. Normalize and apply gamma.

```python

gamma = tl.load(g_ptr + col_offsets, mask=mask, other=0.0).to(tl.float32)

y = h * rstd * gamma

```

Gamma is a 1D tensor of shape (H,). Use col_offsets only — no row offset.

  1. Store the normalized output.

```python

tl.store(y_ptr + row_idx * stride + col_offsets, y.to(input_dtype), mask=mask)

```

Same boundary mask as the load.

  1. For H > BLOCK_SIZE, loop over chunks. Two paths:

Pick two-pass. It writes the residual once (which you must do anyway) and reads it back once.

  1. For training, save rstd and the summed residual. The backward kernel needs both. The summed residual is already written by step 4; just store rstd to a (N_rows,) buffer.
  1. Backward (if required). The forward output is y = h * rstd * gamma where h = x + res. The gradient of the loss with respect to x is dL/dh (since dh/dx = 1); the gradient with respect to res is also dL/dh. So dL/dx = dL/dres = drmsnorm_dh, and gradients on the residual stream pass through unchanged. Implement the rmsnorm backward to produce drmsnorm_dh once, then write it to both dx and dres (or accumulate into dx if res aliases x).

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, residual_ptr, gamma_ptr, y_ptr, sum_ptr (the summed-residual output, may alias x_ptr), rstd_ptr (optional, training only), stride, H, eps, and BLOCK_SIZE: tl.constexpr as arguments.
  2. A Python launcher that flattens the leading dimensions, computes the grid as (N_rows,), asserts contiguity on the last dim, extracts strides, picks BLOCK_SIZE based on H, and exposes an in-place vs out-of-place flag for the residual.
  3. A correctness test comparing against a reference (x + residual).pow(2).mean(-1, keepdim=True).add(eps).rsqrt() * (x + residual) * gamma, plus a check that the summed residual buffer matches x + residual exactly. Use torch.allclose(atol=1e-3, rtol=1e-3) for fp16/bf16 and atol=1e-5 for fp32.
  4. A bandwidth benchmark comparing the fused kernel against an unfused baseline (PyTorch add + reference rmsnorm) using triton.testing.do_bench or torch.utils.benchmark.Timer. Report achieved GB/s, not just speedup.
  5. A note on backward — if forward-only, state explicitly that this kernel is forward-only. If backward is included, state how the residual gradient is split.
  6. Comment block documenting epsilon placement, dtype contract for gamma, and the aliasing assumption between x and the summed-output buffer.

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.