Skip to content
Inference Academy

Fused residual-add RMSNorm and SwiGLU, plugged into PyTorch

Write two fused kernels every Llama-style model can use (residual add plus RMSNorm, and SwiGLU), count the memory traffic they save, register them as PyTorch custom operators that work with torch.compile and CUDA graphs, test them properly across shapes and data types, and compare them with eager PyTorch and with torch.compile's own generated kernels.

By

26 min · verified 2026-111 animated diagramPro
Share
Open in ColabRuns on a free T4 GPU: pick Runtime → Change runtime type → T4 GPU.

You now have all the pieces to do what inference engineers actually spend kernel time on: fusing the memory-bound operations around the matmuls. This lesson writes two fused kernels that sit in every Llama-style transformer layer, then makes them usable from a real model: registered with PyTorch, compatible with torch.compile and CUDA graphs, and properly tested.

#Kernel 1: residual add plus RMSNorm

A pre-norm transformer layer does this twice:

python
h = x + residual          # residual add
y = rms_norm(h) * w       # normalise for the next sub-layer
residual = h              # the next add needs h

Counting tensor-sized transfers, as in the fusion lesson: the add reads xx and the residual and writes hh (3), and the norm reads hh twice (once for the sum of squares, once to scale) and writes yy (3). Six in total. Fused, you read xx and the residual, keep hh in registers, and write hh and yy: four. A third less traffic, and one launch instead of two (or more, in eager PyTorch).

What fusing two kernels saves
Interactive

Implementation

GPU memory (HBM)

add3N

read a, read b → write c

norm pass 11N

read c (sum of squares)

norm pass 22N

read c → write y

Traffic per layer

6N

6.29 MB moved · about 1.9 µs

The intermediate tensor is written to memory and read back twice.

Residual add + RMSNorm on a hidden size of 8192 in BF16. N is one activation tensor. These operations do almost no arithmetic, so their time is the bytes they move at 3.35 TB/s.

python
import torch, triton, triton.language as tl

@triton.jit
def add_rmsnorm_kernel(x_ptr, r_ptr, w_ptr, y_ptr, h_ptr, stride, n_cols, eps, BLOCK: tl.constexpr):
    row = tl.program_id(0)
    cols = tl.arange(0, BLOCK)
    mask = cols < n_cols
    x = tl.load(x_ptr + row * stride + cols, mask=mask, other=0.0).to(tl.float32)
    r = tl.load(r_ptr + row * stride + cols, mask=mask, other=0.0).to(tl.float32)
    h = x + r
    tl.store(h_ptr + row * stride + cols, h.to(h_ptr.dtype.element_ty), mask=mask)
    inv = tl.rsqrt(tl.sum(h * h, axis=0) / n_cols + eps)
    w = tl.load(w_ptr + cols, mask=mask, other=0.0).to(tl.float32)
    tl.store(y_ptr + row * stride + cols, (h * inv * w).to(y_ptr.dtype.element_ty), mask=mask)

Details that matter:

  • FP32 inside, input dtype outside. Loads are converted with .to(tl.float32), and stores convert back with h_ptr.dtype.element_ty, so the kernel works for FP16 and BF16 without changes. That's also what the CUDA RMSNorm did by hand.
  • other=0.0 for the masked lanes: zeros add nothing to the sum of squares.
  • One program per row, whole row in one block. Hidden sizes up to about 8,192 fit comfortably. Larger ones would loop over the row in chunks.
  • One stride for every tensor. This kernel assumes xx, the residual and both outputs share a layout. The wrapper below makes sure of that.

A small numerical note: this kernel normalises the FP32 value of hh, while an unfused version normalises hh after it's been rounded to FP16. Results differ in the last bits. Both are fine; just test with a tolerance.

#Kernel 2: SwiGLU

Llama-style MLPs compute down(silu(gate(x))⊙up(x))\text{down}(\text{silu}(\text{gate}(x)) \odot \text{up}(x)). Engines merge the gate and up projections into one matmul with an output of width 2I2I, then split it. The elementwise part is:

python
gate, up = gate_up.chunk(2, dim=-1)       # views, no copy
out = torch.nn.functional.silu(gate) * up

In eager PyTorch that's two kernels: SiLU reads gate and writes a temporary (2 transfers of width II), then the multiply reads the temporary and up and writes the output (3). Fused, it's read gate, read up, write the output: 3 instead of 5.

python
@triton.jit
def swiglu_kernel(gu_ptr, out_ptr, n_inter, stride_gu, stride_out, BLOCK: tl.constexpr):
    row = tl.program_id(0)
    cols = tl.program_id(1) * BLOCK + tl.arange(0, BLOCK)
    mask = cols < n_inter
    g = tl.load(gu_ptr + row * stride_gu + cols, mask=mask, other=0.0).to(tl.float32)
    u = tl.load(gu_ptr + row * stride_gu + n_inter + cols, mask=mask, other=0.0).to(tl.float32)
    out = g * tl.sigmoid(g) * u
    tl.store(out_ptr + row * stride_out + cols, out.to(out_ptr.dtype.element_ty), mask=mask)

Here the grid is 2D: one axis for rows and one for blocks along the intermediate dimension, because II is large (14,336 for an 8B Llama) and you want several programs per row. You could also fuse this into the epilogue of the gate-up matmul, as in the matmul lesson, which removes the gate-up output from memory entirely. That's a harder kernel (each program needs matching gate and up columns), and it's what the best engines do.

Pro content

Keep reading with Inference Academy Pro

Unlock the rest of this lesson, plus every advanced lesson, hands-on lab, the larger playground models and completion certificates.

Still to come in this lesson

  1. Plugging into PyTorch
  2. Testing it properly
  3. Benchmarking against the alternatives
  4. Where these kernels live in real engines
  5. What you can now do
  6. Common mistakes
  7. Exercise
  8. Going deeper

You will be able to answer

  • Unfused, a residual add followed by RMSNorm moves about 6 tensor-sized transfers. How many does the fused kernel move?
  • Why does torch.library.custom_op need a register_fake function?
  • SwiGLU on a gate and up projection of width I: how much traffic does fusing save over silu(gate) times up in eager PyTorch?
  • Your fused RMSNorm matches PyTorch for width 4096 but fails for width 5120. What is the most likely bug?
  • On an [8, 4096] decode-sized input, your fused kernel is barely faster than eager PyTorch. Why?