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.
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.
- 1. Kernel fusion saves time mainly by…
- 2. torch.compile…
- 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 fastThe 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.
- 1. What happens on the first call of a compiled model?
- 2. mode='reduce-overhead' adds…
- 3. Which is a typical fusion?
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 35 minUndergraduate students and practising engineers.How torch.compile works
- 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
ifon 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. - AOTAutograd traces the backward pass ahead of time into a second graph, and decomposes operators into a small core set.
- 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.
- 1. What causes a graph break?
- 2. Which component generates Triton code?
- 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 withexplain. - 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).
- 1. For a tiny decode-time tensor, which helps most?
- 2. For a huge tensor, CUDA graphs alone…
- 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).
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
- J. Ansel et al. (2024). “PyTorch 2: faster machine learning through dynamic Python bytecode transformation and graph compilation.” ASPLOS.
- PyTorch documentation (pytorch.org/docs): torch.compile, TorchDynamo deep dive, TorchInductor.
- J. Reed et al. (2022). “torch.fx: practical program capture and transformation for deep learning in Python.” MLSys.
- T. Chen et al. (2018). “TVM: an automated end-to-end optimizing compiler for deep learning.” OSDI.
- NVIDIA. CUDA Graphs in the CUDA C++ Programming Guide.