Pidoku

Operator Fusion

Module 11 Lesson 11.h 1h 15m Difficulty 4/5

Prerequisites 11.b, 11.e, 2.e


Before you start: words you need#

WordPlain meaning
FusionDoing several operators in one kernel, so the results in between never go back to GPU memory.
HBM round tripWriting a tensor to GPU main memory and reading it back in the next kernel (4.e).
ElementwiseAn operation done to each value on its own, such as add, multiply or SiLU.
ReductionCombining many values into one, such as a sum, max or mean.
Epilogue / prologueExtra work done at the end of a GEMM (on its output) or at the start (on its inputs) inside the same kernel.
Register pressureA kernel needing so many registers per thread that fewer threads fit on an SM, which can slow it down (6.c).
InductorThe part of torch.compile that turns a graph into generated Triton kernels (11.i).

1. What is it?#

Combining several operations into one kernel, so that intermediate results stay in registers or shared memory instead of making a round trip through HBM.

UNFUSED                              FUSED
  kernel 1: read a, write b            one kernel: read a
  kernel 2: read b, write c                        compute all three steps in registers
  kernel 3: read c, write d                        write d
  → 6 trips through HBM, 3 launches  → 2 trips through HBM, 1 launch

For memory-bound operations, which is most of an LLM apart from the large GEMMs, this cuts the very thing that limits speed.

This lesson is the idea: what fusion is, which kinds exist, and what can and cannot be fused. The specific fusions an LLM engine ships, with their measured value, are catalogued in 13.j.


2. Why does it exist?#

Because frameworks describe models as many small operations, and running each one as its own kernel means a separate trip to memory for each. The maths never needed those trips; the programming interface did.

Fusion gives back the performance that the convenient, one-op-at-a-time interface cost, and it also cuts the number of kernel launches (5.d), which matters at small batch.


3. Simple analogy#

Cooking in one pan instead of washing up between steps.

Unfused: fry the onions, tip them into a bowl, wash the pan; fry the garlic, tip it out, wash; then put everything back to combine. Every transfer is a trip to the sink.

Fused: onions in the pan, garlic into the same pan, tomatoes into the same pan. The in-between stages never leave the hob.


4. Tiny example: four passes or one#

The program applies out = relu(x·2 + 1) · w to 32 million values, once as four separate loops (like four eager kernels) and once as a single loop.

Go
// fusion.go — four elementwise ops as four passes over memory, then as one.
package main

import (
	"fmt"
	"time"
)

func bench(f func()) time.Duration {
	f()
	t0 := time.Now()
	for i := 0; i < 3; i++ {
		f()
	}
	return time.Since(t0) / 3
}

func main() {
	const n = 1 << 25 // 32M elements, 128 MB per array
	x, w := make([]float32, n), make([]float32, n)
	a, b, c, out := make([]float32, n), make([]float32, n), make([]float32, n), make([]float32, n)
	for i := range x {
		x[i], w[i] = float32(i%13)-6, 0.5
	}

	unfused := bench(func() {
		for i, v := range x {
			a[i] = v * 2 // pass 1: read x, write a
		}
		for i, v := range a {
			b[i] = v + 1 // pass 2: read a, write b
		}
		for i, v := range b {
			c[i] = max(v, 0) // pass 3: read b, write c  (ReLU)
		}
		for i, v := range c {
			out[i] = v * w[i] // pass 4: read c, read w, write out
		}
	})
	fused := bench(func() {
		for i, v := range x {
			out[i] = max(v*2+1, 0) * w[i] // one pass: read x, read w, write out
		}
	})

	const bytes = n * 4
	fmt.Printf("unfused %v  (9 array passes = %d MB of traffic)\n", unfused.Round(time.Millisecond), 9*bytes>>20)
	fmt.Printf("fused   %v  (3 array passes = %d MB of traffic)\n", fused.Round(time.Millisecond), 3*bytes>>20)
	fmt.Printf("speedup %.2fx\n", float64(unfused)/float64(fused))
}

Output on an Apple M-series laptop:

unfused 37ms  (9 array passes = 1152 MB of traffic)
fused   16ms  (3 array passes = 384 MB of traffic)
speedup 2.26x

Nine passes over memory become three and the arithmetic does not change at all, so the time falls by a large part of that ratio: about 2.3 times rather than the full 3, because the fused loop still does the same arithmetic and the CPU’s prefetchers soften the unfused passes a little.

On a GPU the same experiment, four eager PyTorch elementwise kernels against one fused kernel, behaves the same way, with launch overhead added on top for the unfused version.


5. Technical explanation#

The kinds of fusion#

1. ELEMENTWISE CHAINS ("vertical")
   add → mul → silu → mul   →  one kernel
   Easy and automatic; torch.compile does this well.

2. REDUCTION + ELEMENTWISE
   rmsnorm: square → mean → rsqrt → mul → mul   →  one kernel (11.e)
   Needs a warp/block reduction inside the kernel.

3. GEMM EPILOGUE
   matmul → bias → activation → (quantize) → store
   Done on the accumulators in registers before the output is written once.
   CUTLASS and cuBLASLt support common epilogues directly.

4. GEMM PROLOGUE
   unpack/dequantize weights → matmul
   Essential for 4-bit weights: the packed form is what crosses HBM (11.c, 13.c).

5. HORIZONTAL
   several independent ops on the same input → one bigger op
   q_proj, k_proj, v_proj → qkv_proj;  gate_proj, up_proj → gate_up_proj
   One read of the input instead of three, and better GEMM tiles.

6. ALGORITHMIC
   FlashAttention: matmul → scale → mask → softmax → matmul, all in SRAM (11.f, 13.l).
   Not mechanical: it needed a new algorithm (online softmax) to be possible.

7. ACROSS COMMUNICATION
   all-reduce + residual add + RMSNorm in one kernel, for tensor parallelism (14.c).

What can and cannot be fused#

Can fuse
  elementwise ops on tensors of the same shape
  a reduction with the elementwise work that follows it
  anything elementwise on a GEMM's output (epilogue) or input (prologue)
  ops whose intermediate is used by only the next op

Cannot easily fuse
  two large GEMMs back to back: the second needs the WHOLE first output
     (special "fused MLP" kernels exist for small shapes only)
  ops with a data-dependent shape in between (e.g. top-k routing in MoE)
  anything across a global synchronisation point
  an intermediate that several later ops need (multiple consumers)

The last one is everywhere in a transformer because of the residual connection: the value going into a norm is also needed later for the residual add. Engines solve it by having one kernel write two outputs.

Where the fusion boundaries fall in a layer#

x   = residual + attn_out          elementwise
h   = rmsnorm(x)                   reduction
g,u = h @ W_gate_up                GEMM
a   = silu(g) * u                  elementwise
out = a @ W_down                   GEMM
new_residual = x + out             elementwise, needs x from the first line

The GEMMs are the natural boundaries, so a well-fused version is:

kernel 1: fused_add_rms_norm(residual, attn_out) → x, h          two outputs
kernel 2: GEMM(h, W_gate_up), then silu(g) * u                   epilogue or separate small kernel
kernel 3: GEMM(a, W_down); its output is added to x by the next layer's fused_add_rms_norm

Three or four kernels where eager PyTorch launches ten or more.

Who does the fusing#

Hand-written kernels   the hottest paths in vLLM, SGLang and TensorRT-LLM:
                       fused_add_rms_norm, silu_and_mul, rotary embedding, attention
torch.compile          Inductor fuses elementwise and reduction chains automatically
                       into generated Triton kernels; GEMMs usually go to cuBLAS, or to
                       Triton/CUTLASS templates under mode="max-autotune"
Compiler passes        vLLM adds its own pattern-matching passes on top of Inductor
                       (below)
CUTLASS / cuBLASLt     a GEMM plus a chosen epilogue

vLLM v0.32.0’s compilation PassConfig shows what a production engine fuses through the compiler today: fuse_norm_quant (RMSNorm followed by FP8 or FP4 quantization of its output), fuse_act_quant (SiLU-and-multiply plus quantization), fuse_attn_quant (attention plus output quantization), fuse_allreduce_rms (FlashInfer’s all-reduce plus RMSNorm for tensor parallelism) and enable_qk_norm_rope_fusion (QK-norm plus RoPE). Most are turned on automatically when the model and hardware make them useful; 18.d shows how the compilation pipeline runs.


6. Under the hood: read what the compiler generated#

For the section 4 computation, Inductor generates a Triton kernel shaped like this (simplified):

Python
@triton.jit
def triton_poi_fused_add_mul_relu_0(in_ptr0, in_ptr1, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)
    xmask = xindex < xnumel
    x = tl.load(in_ptr0 + xindex, xmask)        # one load of x
    w = tl.load(in_ptr1 + xindex, xmask)        # one load of w
    t = x * 2.0 + 1.0
    t = tl.maximum(t, 0.0)                      # relu
    tl.store(out_ptr0 + xindex, t * w, xmask)   # one store

The name lists the fused ops; “poi” marks a pointwise kernel. To see the real thing:

Shell
TORCH_LOGS="output_code" python script.py      # prints every generated kernel

Reading the generated code is the fastest way to learn what the compiler actually fused and what it left alone. Do it at least once on a model you care about.


7. Performance implications#

  • Fusion helps memory-bound work and launch-bound work. Elementwise chains, norms, activation glue and small decode-time kernels all gain.
  • It does little for compute-bound work. Fusing the glue between two large prefill GEMMs saves a small fraction of a step the GEMMs dominate.
  • Fusions can make things slower. A kernel that does too much may need more registers than fit, so fewer warps run per SM (6.c), or it may spill to memory. Measure.
  • Most of the gap between a hand-tuned engine and eager PyTorch at small batch is fusion plus CUDA graphs. 13.j breaks that down fusion by fusion.

8. Production implications#

  • Use an engine that already has the fusions. Do not rebuild fused_add_rms_norm yourself.
  • Verify fusion in a profile. Separate mul, add and rsqrt kernels in a decode step mean something is running unfused.
  • New architecture, lost fusions. If a model adds a new operation, the engine’s hand-written kernels and pattern-matching passes will not cover it until someone adds support; until then that part runs as generic code.
  • Fusion changes numerics. Different order of operations, different rounding (11.k). Run your quality checks after changing compile settings.
  • Cache compiled kernels. Inductor’s output is cached on disk; keep that cache across restarts (11.i).

9. Common mistakes#

  1. Assuming eager PyTorch fuses anything. Eager means one kernel per op.
  2. Fusing without measuring. Register pressure can make a fused kernel slower.
  3. Expecting fusion to speed up compute-bound GEMMs.
  4. Ignoring the multiple-consumer constraint. A naive fusion recomputes or re-reads the shared intermediate.
  5. Not re-validating outputs after enabling new fusions or compile modes.
  6. Hand-fusing in Python (writing x.mul_(2).add_(1) in place) and expecting it to be one kernel. In-place ops save memory, not launches.

10. Hands-on exercise#

  1. Run fusion.go. Extend the chain to eight operations. Does the speedup keep growing in proportion? Why does it level off?
  2. In PyTorch, compile the same function with torch.compile and run with TORCH_LOGS="output_code". Confirm the generated kernel has two loads and one store.
  3. Time Q, K and V as three GEMMs and as one concatenated GEMM at M = 1 and M = 2048. Explain both results.
  4. Profile one decode step of a model in eager Hugging Face Transformers and in vLLM. List the ten most frequent kernels in each and match the vLLM ones to section 5’s fusion kinds.
  5. Build a case where fusion is slower: fuse so many operations into one Triton kernel that it spills registers, and measure.

11. Interview questions#

  1. What is operator fusion, and why does it help memory-bound operations so much?
  2. Name six kinds of fusion and give a transformer example of each.
  3. Why can two large GEMMs in a row not normally be fused?
  4. How does the residual connection constrain fusion, and how do engines work around it?
  5. What does vLLM fuse through its compiler passes, and why are several of them about quantization?
  6. How would you verify that a fusion is actually happening in production?
  7. When can fusion make things slower?

12. Further reading#

Checked on 12 November 2026.

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in