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 Sandip Maity, Applied AI Engineer
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:
h = x + residual # residual add
y = rms_norm(h) * w # normalise for the next sub-layer
residual = h # the next add needs hCounting tensor-sized transfers, as in the fusion lesson: the add reads and the residual and writes (3), and the norm reads twice (once for the sum of squares, once to scale) and writes (3). Six in total. Fused, you read and the residual, keep in registers, and write and : four. A third less traffic, and one launch instead of two (or more, in eager PyTorch).
Implementation
GPU memory (HBM)
read a, read b → write c
read c (sum of squares)
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.
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 withh_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.0for 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 , 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 , while an unfused version normalises 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 . Engines merge the gate and up projections into one matmul with an output of width , then split it. The elementwise part is:
gate, up = gate_up.chunk(2, dim=-1) # views, no copy
out = torch.nn.functional.silu(gate) * upIn eager PyTorch that's two kernels: SiLU reads gate and writes a temporary (2 transfers of width ), 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.
@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 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
- Plugging into PyTorch
- Testing it properly
- Benchmarking against the alternatives
- Where these kernels live in real engines
- What you can now do
- Common mistakes
- Exercise
- 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?