Pidoku

Kernel and Operator Fusion

Module 13 Lesson 13.j 1h Difficulty 3/5

Prerequisites 11.h, 4.d, 13.a


Before you start: words you need#

WordPlain meaning
KernelOne program launched on the GPU (5.b). Eager PyTorch launches roughly one per operation.
FusionDoing several operations inside one kernel, so the intermediate results stay in registers or shared memory instead of going to HBM and back.
Elementwise / reduction opAn op that touches each value once (add, multiply, SiLU) or combines a row into one number (sum, mean). Both are memory-bound: they move far more bytes than they compute.
Epilogue / prologueExtra work done at the end (epilogue) or start (prologue) of a matrix-multiply kernel, in registers: add a bias, apply an activation, quantize, or unpack 4-bit weights.
Horizontal fusionMerging several independent matrix multiplies that read the same input (Q, K and V projections) into one bigger one.
Register pressureWhen a kernel needs so many registers per thread that fewer threads fit on an SM, or values spill to slower memory.
InductorThe code generator behind torch.compile; it writes fused Triton kernels automatically (13.m).

11.h covered fusion mechanically. This lesson treats it as an optimization decision: which fusions matter in an LLM, roughly what each is worth, how serving engines apply them in 2026, and when fusion does not help.


1. Problem → Why → Optimization#

PROBLEM   A transformer layer in eager PyTorch runs ~15 kernels, most of them
          memory-bound elementwise or reduction ops, each doing a full round
          trip to HBM, and each paying a launch.
WHY       Framework granularity (one op = one kernel) is much finer than the
          granularity at which HBM round trips are worth paying.
OPTIMIZE  Combine neighbouring operations into single kernels so intermediates
          stay in registers or shared memory.

TRADE-OFFS
  ✓ 2–4× on the fused ops; 10–25% end to end is typical
  ✓ fewer launches (compounds with CUDA graphs, 13.k)
  ✗ more register pressure → possibly lower occupancy
  ✗ slightly different numerics (different rounding order)
  ✗ engineering effort for unusual architectures

WHEN TO USE   Always, for the standard fusions. Your engine already does them.
WHEN NOT TO   When the ops are compute-bound GEMMs with nothing cheap to absorb,
              or when the fused kernel spills registers.

2. Why does it matter? The fusion catalogue for LLMs#

The fusions that matter, roughly in order of value. The shares are illustrative for a dense model at decode; measure your own (exercise C).

#  Fusion                       What it combines                    Effect
1  add + RMSNorm                residual add, then RMSNorm          ~10 tensor passes → 4
2  SiLU-and-mul                 SiLU(gate) × up                     3 passes → 1
3  QKV projection               3 GEMMs → 1 (horizontal)            x read once
4  gate_up projection           2 GEMMs → 1 (horizontal)            x read once
5  GEMM epilogue                bias / activation / residual        output written once
6  quantization fusions         RMSNorm+quant, SiLU-mul+quant,      no separate quant kernel
                                attention+quant (FP8/NVFP4, 13.e)
7  RoPE + KV-cache write        rotate K, store K/V in the paged    2 kernels → 1
                                cache (sometimes with QK-norm)
8  FlashAttention               the whole attention block           ~6 kernels → 1 (13.l)
9  dequant + GEMM (prologue)    unpack INT4 weights in registers    essential for W4A16
10 all-reduce + RMSNorm         TP communication + next norm        one kernel (FlashInfer)
11 sampling                     temperature/top-k/top-p/sample      5 kernels → 1–2

Together these account for a large share of the gap between naive PyTorch and a production engine. The other big shares are batching and paged KV (12.j, 12.l).


3. Simple analogy#

A production line versus separate workshops.

Separate workshops: each stage receives a crate, does one operation, packs the item back into a crate, and ships it to the next workshop. Half the effort is packing and shipping.

Production line: the item moves along a belt through five operations without ever being packed.

The crate is HBM. The belt is registers.


4. Tiny example: the highest-value fusion#

add + RMSNorm appears twice per layer:

Python
# UNFUSED (what eager PyTorch does)
def unfused(x, residual, weight, eps=1e-6):
    x = x + residual                      # read x, read residual, write t1
    var = x.pow(2).mean(-1, keepdim=True) # read t1, write t1²; read t1², write var (tiny)
    x_n = x * torch.rsqrt(var + eps)      # read t1, write t3
    return x_n * weight, x                # read t3, write out; also return t1
# ~10 full-tensor reads/writes, ~6 kernel launches

# FUSED (one kernel)
#   load a row of x and residual into registers
#   add
#   sum of squares by warp reduction
#   rsqrt, multiply by weight
#   store BOTH the normalized output and the new residual
# 2 reads + 2 writes, 1 launch

The arithmetic for one decode step at batch 64, hidden size 8192, BF16:

tensor size        64 × 8192 × 2 B = 1 MiB
unfused traffic    ~10 MiB, ~6 launches
fused traffic        4 MiB, 1 launch           → 2.5× fewer bytes, 6× fewer launches

At decode the tensor is so small that the launches cost more than the bytes:
moving 10 MiB at ~3 TB/s takes ~3.5 µs; six launches cost ~5 µs each on the CPU.

So at decode this fusion mostly saves launches; at prefill (thousands of tokens) it mostly saves bandwidth. Either way it wins.


5. Technical explanation#

Why add + RMSNorm returns two things#

The residual stream is needed again by the next residual add:

x_new = x + attn_out          ← needed later
h     = rmsnorm(x_new)        ← fed to the FFN

Both come out of the same kernel. Writing both costs one extra store
but saves a full re-read later.

This “return the intermediate too” pattern is common in fused kernels and is why their signatures look odd.

Epilogue fusion in GEMM#

CUTLASS and cuBLASLt let you attach an epilogue:

  D = activation(alpha × A×B + beta × C + bias)

executed in registers before the accumulator is written to HBM.

Savings: one full read + write of the output tensor.
For a (2048, 14336) BF16 output that is ~117 MB of traffic avoided,
per matrix, per layer.

Quantized serving adds one more epilogue: convert the output to FP8 or NVFP4 with its scale, so the next GEMM can read it directly (13.e, 13.g).

Prologue fusion (for quantized weights)#

  load INT4 weights from HBM
  unpack + dequantize IN REGISTERS
  feed the tensor cores

Without this you would write a full BF16 weight tensor to HBM first —
defeating the purpose.

Prologue fusion is not an optimization for W4A16; it is a requirement (Marlin and similar kernels, 13.f).

Horizontal fusion (concatenated GEMMs)#

q = x @ Wq   (4096 → 4096)
k = x @ Wk   (4096 → 1024)      →   qkv = x @ [Wq|Wk|Wv]   (4096 → 6144)
v = x @ Wv   (4096 → 1024)           then split the output

Benefits:
  - x is read once instead of three times
  - one launch instead of three
  - one larger, better-shaped GEMM (better tiles, more blocks in flight)

Done at model load time by concatenating the weights. The gain is largest at small batch, where launches and small GEMMs dominate.

Communication fusion#

With tensor parallelism (14.c), each layer ends in an all-reduce followed by RMSNorm (and often a quantize). FlashInfer provides a kernel that does the all-reduce, residual add, norm and optional quantize in one pass over the data; vLLM enables it with fuse_allreduce_rms on supported GPUs.

How engines apply fusions in 2026#

Two ways, usually combined:

  • Hand-written fused kernels for the hot paths: fused_add_rms_norm, silu_and_mul, attention, MoE.
  • Compiler passes that pattern-match the graph and swap in fused kernels. vLLM’s torch.compile integration (13.m, 18.d) has passes such as fuse_norm_quant (RMSNorm + quant), fuse_act_quant (SiLU-mul + quant), fuse_attn_quant (attention output + quant), fuse_allreduce_rms and a QK-norm + RoPE fusion, enabled automatically where the platform supports them. v0.32.0 removed the older sequence-parallel and AsyncTP (GEMM + communication) passes.

When fusion does not help#

1. The ops are compute-bound.
   Fusing an activation into a big GEMM saves the output round trip —
   worth it — but "fusing" two GEMMs back to back saves nothing,
   because the second needs the whole intermediate.

2. Register pressure causes spilling.
   A fused kernel needing 200 registers per thread may drop occupancy
   below the point where latency is hidden (6.c). Measure.

3. The intermediate has several consumers.
   Fusion must then recompute it or write it anyway.

4. The ops are tiny next to everything else.
   Amdahl's law (13.a).

6. Under the hood#

A fused RMSNorm kernel:

one block per token (a row of length d)
  each thread loads d/blockDim elements as 16-byte vectors (8 BF16 values)
  add the residual in registers
  partial sum of squares
  warp reduction (__shfl_down_sync) → block reduction (shared memory)
  broadcast rsqrt through shared memory
  each thread scales its elements and stores both outputs

The data is read from HBM once and written once. Everything in between happens in registers.


7. Performance implications#

An illustrative budget for a 70B decode step (your profile will differ):

Eager PyTorch, no fusion                      100%
+ add + RMSNorm fused                          -12%
+ SiLU-and-mul fused                            -6%
+ QKV and gate_up horizontally fused            -7%
+ GEMM epilogue fusion                          -4%
+ FlashAttention                               -10%
+ fused RoPE + cache write                      -2%
                                              ──────
                                               ~59%   (1.7×)
+ CUDA graphs (fewer kernels to launch)        -12%
                                               ~47%   (2.1×)

The pattern to remember: fusion and CUDA graphs compound, because both attack the same per-kernel overhead from different sides.


8. Production implications#

  • Your engine already does these. Verify by profiling (22.h): you should see kernels like fused_add_rms_norm_kernel, silu_and_mul_kernel and a flash attention kernel, not aten::add / aten::mul / aten::rsqrt.
  • Custom architectures lose fusions. A new activation or norm variant falls back to unfused ops. Budget for torch.compile or a custom kernel.
  • Quantized models depend on the quant fusions. Without them, every FP8 GEMM is preceded by a separate quantize kernel that eats much of the gain.
  • torch.compile covers the elementwise and reduction fusions automatically; GEMM epilogues and communication fusions still come mostly from hand-written or library kernels.
  • Validate numerics after enabling a fusion. The rounding order changes.

9. Common mistakes#

  1. Assuming eager PyTorch fuses. It does not.
  2. Fusing without measuring. Register pressure can make the fused kernel slower.
  3. Fusing compute-bound ops and expecting a gain.
  4. Writing custom kernels before trying torch.compile.
  5. Not checking that the engine’s fusions apply to your model’s architecture or quantization format.
  6. Forgetting the quantize step when estimating the gain from FP8 — an unfused quantize can erase it.

10. Hands-on exercise#

A. Measure the top fusion. Implement add + RMSNorm unfused, with torch.compile, and with an existing fused kernel (from vLLM or FlashInfer). Benchmark all three at batch 1, 64 and 4096 tokens. Report time and effective GB/s. Where do launches dominate, and where do bytes?

B. Horizontal fusion. Implement QKV as three GEMMs and as one. Measure at batch 1 and batch 2048. Explain why the gain differs.

C. Find unfused ops. Profile a model in eager mode. List every kernel by time. Identify which memory-bound kernels could be fused with a neighbour. Estimate the total win with Amdahl’s law.

D. Register pressure. Write a deliberately over-fused kernel (10 elementwise ops) in Triton (6.e) and measure register use and occupancy. Does it get slower at some point?

E. Epilogue fusion. Using cuBLASLt or CUTLASS, run a GEMM with and without a fused bias + activation epilogue. Measure the difference.


11. Interview questions#

  1. List the most valuable fusions in an LLM and why each helps.
  2. Why does a fused add + RMSNorm return two tensors?
  3. What is prologue fusion and why is it mandatory for W4A16?
  4. What is horizontal fusion and why does its benefit depend on batch size?
  5. Why do quantized models need quantize fusions to see their full gain?
  6. When does fusion make things slower?
  7. How would you verify that fusion is active in a production engine?

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