Foundations to Frontier
Tests
C. Programming, Tools and HPC › C5 High-Performance Computing

Kernel Fusion and torch.compile

Most operations in a neural network are memory-bound element-wise or reduction steps, and in eager mode each one is a separate kernel that reads its inputs from GPU memory and writes a full-size result. Kernel fusion combines chains of such operations into one kernel that keeps intermediates in registers, and CUDA graphs remove per-kernel launch overhead. torch.compile automates both: TorchDynamo captures Python into FX graphs (breaking the graph on data-dependent Python), AOTAutograd builds the backward graph, and TorchInductor fuses operations and generates Triton kernels. This topic covers why fusion works (roofline, C5.3), what can and can't be fused, graph breaks and recompilations, compile modes, and how to measure the gain. In the exercises you build a tiny tracing compiler that fuses element-wise chains, reductions and matmul epilogues and generates Python code, detecting graph breaks; then you model eager, CUDA-graph and fused execution time for common chains across tensor sizes.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

One trip instead of nine

Imagine a recipe with nine steps, where after each step you put the bowl back in the fridge and take it out again for the next one. Fusing the steps means taking the bowl out once, doing all nine steps on the counter, and putting the result away once. Computers are like this: moving data in and out of memory costs much more than the steps themselves. Kernel fusion does many steps on the data while it’s close at hand, and torch.compile does the fusing for you.

Kernel fusion: GELU as 9 kernels or 1
orange: launch overhead · blue: moving bytes (scale: slowest mode = full width)
eager: 41.7 µs
eager + CUDA graph: 10.2 µs
fused: 4.5 µs
bytes moved: eager 11.53 MB vs fused 1.05 MB (FP16, A100 bandwidth, 4 µs per eager launch)
For small tensors (decode, small batches) the time is almost all launch overhead: capturing the 9 kernels in a CUDA graph (torch.compile mode="reduce-overhead") recovers most of it. For large tensors the 9 full-size intermediates dominate: only fusion, which keeps them in registers, removes that traffic. torch.compile does both.
Why engineers care

Fusion is often the cheapest big speed-up for training and inference: a one-line torch.compile can make a model 1.3–2× faster with no change to the mathematics. For deployment on robots and edge devices, compiled and fused graphs (TorchInductor, TensorRT, XLA) are how models meet latency budgets.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Kernel fusion saves time mainly by…
  2. 2. torch.compile…
  3. 3. In the demo, for tiny tensors most of the eager time is…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

Using torch.compile

model = torch.compile(model)                          # default: Inductor backend, fuses and generates Triton
model = torch.compile(model, mode="reduce-overhead")  # also captures CUDA graphs (great for small batches)
model = torch.compile(model, mode="max-autotune")     # autotunes matmul/conv kernels too (slower to compile)
out = model(x)                                        # first call compiles (seconds); later calls are fast

The first call traces and compiles; subsequent calls with the same input properties reuse the compiled code. New shapes, dtypes or Python values that the graph depends on trigger a recompilation (mark changing dimensions as dynamic, torch._dynamo.mark_dynamic, or dynamic=True).

What fuses

  • Element-wise chains (activation functions, scaling, bias, residual adds): into one kernel.
  • Reductions with their producers and consumers (softmax, LayerNorm, RMSNorm: one kernel per row when a row fits on chip).
  • Matmul epilogues: bias and activation applied as the matmul’s tile is written.
  • Not across: large matmuls with each other (they’re compute-bound library calls), or anything requiring global synchronization.
📝 Quick check (Level 1)
0/3 answered
  1. 1. What happens on the first call of a compiled model?
  2. 2. mode='reduce-overhead' adds…
  3. 3. Which is a typical fusion?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.

How torch.compile works

  1. TorchDynamo runs your Python function under a frame-evaluation hook, records tensor operations into an FX graph, and guards on the assumptions it made (shapes, dtypes, Python values). Code it can’t trace, such as data-dependent if on tensor values, .item(), printing tensors or unsupported libraries, causes a graph break: the graph so far is compiled, the Python runs eagerly, and tracing resumes after it.
  2. AOTAutograd traces the backward pass ahead of time into a second graph, and decomposes operators into a small core set.
  3. TorchInductor schedules the graph, groups operations into fused kernels, and emits Triton (GPU) or C++/OpenMP (CPU) code; matmuls and convolutions go to cuBLAS/cuDNN or autotuned Triton templates.

torch._dynamo.explain(fn)(x) lists graph breaks; TORCH_LOGS="graph_breaks,recompiles,output_code" shows them and the generated kernels.

🐍 Exercise 1: a tiny tracing compiler
Trace a Python function over symbolic tensors into a graph (element-wise ops, last-axis reductions, matmul, constants; comparisons produce traced booleans whose truth value raises a graph break). Count eager kernels and bytes, group element-wise chains, reductions and matmul epilogues into fused kernels, generate Python code for each fused kernel, and check the compiled GELU, LayerNorm and matmul + bias + GELU against NumPy.
📝 Quick check (Level 2)
0/3 answered
  1. 1. What causes a graph break?
  2. 2. Which component generates Triton code?
  3. 3. Why does a new input shape cause recompilation?

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

When does fusion pay off?

For an element-wise chain of k kernels moving B_eager bytes in eager mode and B_fused bytes fused, with launch overhead L per kernel and bandwidth W: t_eager ≈ kL + B_eager/W and t_fused ≈ L + B_fused/W. Small tensors are launch-bound (CUDA graphs recover most of the gap); large tensors are bandwidth-bound (only fusion helps, by roughly B_eager/B_fused). The crossover is where the eager bytes take as long as the launches: about kLW/b_eager elements, where b_eager is the eager bytes per element.

Pitfalls

  • Graph breaks in the training step (logging .item(), data-dependent Python) split it into many small graphs; check with explain.
  • Recompilation storms from changing shapes (variable sequence lengths): pad to buckets or mark dimensions dynamic.
  • Compile time: seconds to minutes; cache artifacts, and compile only the hot model, not the whole script.
  • Numerical differences from reordered or fused floating-point operations are expected at the level of rounding (C2.4).
📝 Quick check (Level 3)
0/3 answered
  1. 1. For a tiny decode-time tensor, which helps most?
  2. 2. For a huge tensor, CUDA graphs alone…
  3. 3. Variable sequence lengths can cause…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Fusion, measured

Exercise 1. The tracing compiler turns tanh-approximate GELU into 9 eager kernels or 1 fused kernel that reads x and writes y once (eager moves more than 7× the bytes), LayerNorm (7 kernels with two reductions) into one row-wise kernel, and matmul + bias + GELU into one matmul with an epilogue. The generated Python code reproduces NumPy, and relu(x) if sum(x) > 0 else tanh(x) raises a graph break.

Exercise 2: launch-bound versus bandwidth-bound. Kernel and byte counts from the compiler, FP16 on an A100 (2.04 TB/s), 4 µs per eager launch and 0.5 µs per kernel inside a CUDA graph:

Chain (eager → fused kernels) 1 × 4096: eager / +graph / fused (µs) 65 536 × 4096: eager / +graph / fused (ms) fused speed-up small / large
GELU (9 → 1) 36.1 / 4.6 / 4.0 5.83 / 5.80 / 0.53 9.0× / 11.0×
LayerNorm (7 → 1) 28.0 / 3.5 / 4.0 2.40 / 2.37 / 0.53 7.0× / 4.5×
bias + dropout + residual + LayerNorm (10 → 1) 40.1 / 5.1 / 4.0 4.52 / 4.48 / 1.06 10.0× / 4.3×
softmax (5 → 1) 20.0 / 2.5 / 4.0 2.13 / 2.11 / 0.53 5.0× / 4.0×

At 1 × 4096, essentially all eager time is launch overhead and CUDA graphs alone recover it (even beating a single fused launch for LayerNorm and softmax). At 65 536 × 4096, launches are under 2% of the time and CUDA graphs change nothing; fusion’s gain equals the reduction in bytes (11× for GELU, about 4.5× for normalizations). For GELU the crossover is near 1.6 million elements (about 400 rows of 4096).

🐍 Exercise 2 (research): launch-bound versus bandwidth-bound
Reuse the compiler's kernel and byte counts for GELU, LayerNorm, bias + dropout + residual + LayerNorm and softmax; model eager, eager with CUDA graphs and fused execution time on an A100 for tensor sizes from one decode token to long-context training; identify when launches and when bytes dominate and what each technique buys.

Fusion in AI, robotics and aerospace

  • Training: torch.compile on transformer blocks typically gives 1.3–2× end-to-end, mostly from fused normalizations, activations and attention.
  • Inference servers: CUDA graphs plus fusion for low-latency decoding.
  • Edge deployment: TensorRT and TVM fuse layers for Jetson-class devices; XLA does the same for JAX and TPUs.
  • Scientific computing: fused stencil and update kernels in simulation codes follow the same principle of minimizing memory passes.

References

  1. J. Ansel et al. (2024). “PyTorch 2: faster machine learning through dynamic Python bytecode transformation and graph compilation.” ASPLOS.
  2. PyTorch documentation (pytorch.org/docs): torch.compile, TorchDynamo deep dive, TorchInductor.
  3. J. Reed et al. (2022). “torch.fx: practical program capture and transformation for deep learning in Python.” MLSys.
  4. T. Chen et al. (2018). “TVM: an automated end-to-end optimizing compiler for deep learning.” OSDI.
  5. NVIDIA. CUDA Graphs in the CUDA C++ Programming Guide.