Pidoku

Graph Optimization and Compilers

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

Prerequisites 11.b, 11.h


Before you start: words you need#

WordPlain meaning
Compiler passOne rewrite applied to the whole graph, such as “remove unused nodes”. A compiler runs many in a row.
IRIntermediate representation: the compiler’s own format for the program while it rewrites it.
Constant foldingWorking out, at compile time, anything that depends only on constants.
Dead code eliminationDeleting nodes whose results are never used.
AutotuningTrying several versions of a kernel (tile sizes, layouts) on the real GPU and keeping the fastest.
AOT / JITAhead-of-time (compile before serving starts) or just-in-time (compile on first use).
GuardA check, run on each call, that the inputs still match what a compiled version assumed (shape, dtype, device).
CodegenCode generation: writing the actual kernel source (Triton, C++, PTX) for the optimised graph.

1. What is it?#

Taking a model’s graph (11.b), rewriting it into a faster graph that computes the same thing, and generating code for it.

model code → [capture graph] → [rewrite passes] → [schedule + fuse] → [codegen] → kernels

The systems that do this, in 2026: TorchInductor behind torch.compile, AOTInductor behind torch.export, TensorRT for fixed-shape models, XLA for JAX and TPUs, ONNX Runtime, Apache TVM and its descendants, and each accelerator vendor’s own compiler.

Facts checked on 12 November 2026.


2. Why does it exist?#

Because the graph a person writes is organised for reading, and the graph a GPU wants is organised for memory traffic, kernel count and tile shapes. A compiler bridges the two automatically, so you get much of the benefit of hand-tuning without hand-tuning every model.


3. Simple analogy#

A logistics planner rewriting a delivery route. The route you would naturally describe (“customer A, then B, then C”) is not the route with the fewest miles. The planner reorders stops, merges stops on the same street, drops a pointless detour and picks the van size. Same deliveries, less fuel.

Constant folding is “you always pass the depot, so load that in advance”. Fusion is “three stops on one street become one”. Autotuning is “drive both routes once and keep the faster”.


4. Tiny example: a toy compiler#

The program takes a small block, gelu((x @ w) · (1/√64) + b), written with some waste a person might leave in: a constant computed at run time, an add of zero, and a debug sum nobody reads. It runs four passes and counts the kernels left.

Go
// passes.go — a toy graph compiler: constant folding, algebraic simplification,
// dead code elimination and elementwise fusion, applied to a tiny MLP block.
package main

import (
	"fmt"
	"math"
	"strings"
)

type node struct {
	name, op string
	args     []string
	val      float64 // for "const"
}

func show(title string, g []node) {
	fmt.Printf("%s (%d nodes)\n", title, len(g))
	for _, n := range g {
		if n.op == "const" {
			fmt.Printf("  %-6s = const %g\n", n.name, n.val)
		} else {
			fmt.Printf("  %-6s = %s(%s)\n", n.name, n.op, strings.Join(n.args, ", "))
		}
	}
}

func main() {
	g := []node{
		{name: "x", op: "input"}, {name: "w", op: "input"}, {name: "b", op: "input"},
		{name: "c64", op: "const", val: 64},
		{name: "sq", op: "sqrt", args: []string{"c64"}},    // depends only on constants
		{name: "scale", op: "recip", args: []string{"sq"}}, // so does this
		{name: "y0", op: "matmul", args: []string{"x", "w"}},
		{name: "y1", op: "mul", args: []string{"y0", "scale"}},
		{name: "y2", op: "add", args: []string{"y1", "b"}},
		{name: "y3", op: "gelu", args: []string{"y2"}},
		{name: "zero", op: "const", val: 0},
		{name: "y4", op: "add", args: []string{"y3", "zero"}}, // x + 0
		{name: "dbg", op: "sum", args: []string{"y2"}},        // never used
		{name: "out", op: "output", args: []string{"y4"}},
	}
	show("original", g)

	// 1. Constant folding: evaluate nodes whose inputs are all constants.
	consts := map[string]float64{}
	for i, n := range g {
		if n.op == "const" {
			consts[n.name] = n.val
			continue
		}
		if a, ok := consts[first(n.args)]; ok && len(n.args) == 1 {
			v := map[string]func(float64) float64{"sqrt": math.Sqrt, "recip": func(x float64) float64 { return 1 / x }}[n.op]
			if v != nil {
				g[i] = node{name: n.name, op: "const", val: v(a)}
				consts[n.name] = g[i].val
			}
		}
	}
	// 2. Algebraic simplification: y = add(x, 0) becomes a rename of x.
	rename := map[string]string{}
	for _, n := range g {
		if n.op == "add" && consts[n.args[1]] == 0 && isConst(g, n.args[1]) {
			rename[n.name] = n.args[0]
		}
	}
	for i := range g {
		for j, a := range g[i].args {
			if r, ok := rename[a]; ok {
				g[i].args[j] = r
			}
		}
	}
	// 3. Dead code elimination: keep only nodes reachable from the output.
	live := map[string]bool{"out": true}
	for i := len(g) - 1; i >= 0; i-- {
		if live[g[i].name] {
			for _, a := range g[i].args {
				live[a] = true
			}
		}
	}
	var kept []node
	for _, n := range g {
		if live[n.name] {
			kept = append(kept, n)
		}
	}
	show("\nafter folding, simplification, dead code elimination", kept)

	// 4. Fusion: a matmul followed by a chain of elementwise ops becomes one kernel.
	elementwise := map[string]bool{"mul": true, "add": true, "gelu": true}
	var kernels []string
	for _, n := range kept {
		switch {
		case n.op == "matmul":
			kernels = append(kernels, "matmul")
		case elementwise[n.op] && len(kernels) > 0:
			kernels[len(kernels)-1] += "+" + n.op // epilogue
		}
	}
	fmt.Printf("\nkernels to launch: %d  %v\n", len(kernels), kernels)
}

func first(s []string) string {
	if len(s) == 0 {
		return ""
	}
	return s[0]
}

func isConst(g []node, name string) bool {
	for _, n := range g {
		if n.name == name {
			return n.op == "const"
		}
	}
	return false
}

Output:

original (14 nodes)
  x      = input()
  w      = input()
  b      = input()
  c64    = const 64
  sq     = sqrt(c64)
  scale  = recip(sq)
  y0     = matmul(x, w)
  y1     = mul(y0, scale)
  y2     = add(y1, b)
  y3     = gelu(y2)
  zero   = const 0
  y4     = add(y3, zero)
  dbg    = sum(y2)
  out    = output(y4)

after folding, simplification, dead code elimination (9 nodes)
  x      = input()
  w      = input()
  b      = input()
  scale  = const 0.125
  y0     = matmul(x, w)
  y1     = mul(y0, scale)
  y2     = add(y1, b)
  y3     = gelu(y2)
  out    = output(y3)

kernels to launch: 1  [matmul+mul+add+gelu]

Run eagerly, that block launches about eight kernels (including the sqrt and reciprocal on tensors, the + 0 and the unused sum). After four passes it is one GEMM with an epilogue. A real compiler can go one step further and fold the 0.125 into the GEMM’s own scaling factor.

In PyTorch the same thing is one line, and the passes happen inside:

Python
compiled = torch.compile(f, mode="max-autotune")

5. Technical explanation#

The catalogue of passes#

GRAPH LEVEL
  Constant folding           evaluate constant subgraphs at build time
  Dead code elimination      drop nodes nobody uses
  Common subexpressions      compute a repeated subgraph once
  Algebraic simplification   x·1 → x;  (Aᵀ)ᵀ → A;  a split followed by a concat → nothing
  Operator substitution      replace a pattern with a faster equivalent kernel
  Fusion                     11.h
  Layout assignment          choose layouts for the whole graph, fewest transposes (11.g)
  Memory planning            reuse buffers whose lifetimes do not overlap
  Weight prepacking          reorder weights once for the chosen kernel

KERNEL LEVEL
  Tiling                     tile sizes matched to shared memory and registers
  Vectorisation              wide loads and stores
  Software pipelining        overlap the next load with the current compute
  Autotuning                 time candidates on the real GPU, cache the winner

Three ways to get kernels#

AHEAD OF TIME (TensorRT, torch.export + AOTInductor, TVM)
  Build once, offline, for a fixed model, shape range and GPU type.
  + the whole graph is visible; heavy autotuning; nothing to compile at serve time
  - builds take minutes; rebuild for each GPU architecture and shape range

JUST IN TIME (torch.compile)
  Compile on first call for each set of input shapes, guard, cache.
  + works on ordinary Python model code; incremental
  - first-call delay; recompiles when shapes change (11.j); graph breaks

RUNTIME LIBRARY (cuBLAS, cuDNN)
  Pick a pre-built kernel per call from the shape.
  + no build step
  - nothing is optimised across operators

LLM engines mix all three. vLLM compiles the model with torch.compile plus its own fusion passes at startup, caches the result on disk, captures CUDA graphs for decode, and calls hand-written and library kernels for attention, GEMMs and MoE (18.d).

How torch.compile works#

TorchDynamo     reads the Python bytecode as it runs and records PyTorch calls into FX graphs;
                stops with a "graph break" at anything it cannot follow
AOTAutograd     makes the graph functional (no in-place surprises); the training-only part
                (building the backward pass) is skipped for inference
TorchInductor   lowers the graph: fuses, plans memory, writes Triton kernels for GPUs
                (C++/OpenMP for CPUs), and calls cuBLAS or templates for GEMMs
Triton          compiles each kernel to PTX, then to machine code (SASS)

The modes:

default                      fusion and codegen, moderate compile time
reduce-overhead              + CUDA graphs (5.f), for small batches
max-autotune                 + autotuned GEMM and convolution templates, + CUDA graphs
max-autotune-no-cudagraphs   the same autotuning without CUDA graphs

Graph breaks are the main practical problem. A .item(), a print, data-dependent Python control flow or an unsupported library call splits the graph, and no optimisation crosses the split. List them, and list recompilations, with:

Shell
TORCH_LOGS="graph_breaks,recompiles" python serve.py

fullgraph=True turns any graph break into an error, which is how you keep a hot path clean.

Ahead of time: torch.export and AOTInductor#

torch.export captures the whole program into one graph with no Python left, failing rather than breaking the graph. AOTInductor then compiles that graph into a packaged artifact (a .pt2 file) that can be loaded and run from Python or C++ without compiling at serve time. It is the replacement for TorchScript, which was deprecated in PyTorch 2.10.

What happened to TensorRT-LLM engines#

TensorRT-LLM used to be the textbook AOT example: convert a checkpoint, run trtllm-build with a fixed maximum batch size and sequence lengths, and serve the resulting engine file. That is no longer how it works. PyTorch became TensorRT-LLM’s default backend in 1.0, and the TensorRT engine backend has since been removed: current releases load Hugging Face checkpoints directly with no engine-build step, and use hand-written and generated kernels inside a PyTorch runtime (15.c). TensorRT itself still builds engines for fixed-shape models such as vision encoders.


6. Under the hood: memory planning#

Naive:    every intermediate gets its own buffer
          peak = sum of all intermediates

Planned:  compute each tensor's live range (first write to last read)
          tensors whose ranges do not overlap share one buffer
          peak = the most bytes alive at any one moment

For a transformer layer, the planned peak is a small multiple of one activation tensor instead of the sum of every intermediate. For long-context prefill, when activations are hundreds of megabytes, this decides whether the step fits beside the KV cache. Section 4 of 11.b computed the live ranges for a four-node graph; a compiler does the same for thousands.


7. Performance implications#

Rough, workload-dependent gains over eager PyTorch for LLM inference:

torch.compile, default                 modest (often 10–30%)
torch.compile, reduce-overhead         larger at small batch, from CUDA graphs
a serving engine (vLLM, SGLang)        several times, mostly NOT from compilation

Most of what a serving engine gains over a plain model.generate() loop comes from continuous batching (12.j) and the paged KV cache (12.l): scheduling and memory management, not code generation. Compilation is a tens-of-percent lever; scheduling is a several-times lever. If your server runs at batch 2 because of its scheduler, a better compiler is not the fix.


8. Production implications#

  • Compile before traffic, and cache the result. Inductor keeps its output in a cache directory (TORCHINDUCTOR_CACHE_DIR); vLLM keeps its compiled artifacts under its own cache directory. Put them on persistent storage or bake them into the image, keyed by model, GPU type, shapes and library versions.
  • Rebuild for each GPU architecture. Kernels tuned for an H100 are not valid for a B200.
  • Watch recompilations. Each recompile stalls requests for seconds. After recompile_limit recompilations of one function (default 8; the older name cache_size_limit still works), Dynamo logs torch._dynamo hit config.recompile_limit (8) and stops compiling that function, which then runs eagerly from then on. Alert on that log line.
  • Validate outputs after changing compiler settings. Fusion and kernel choice change rounding (11.k).

9. Common mistakes#

  1. Compiling in the request path. Seconds to minutes of stall for the first unlucky users.
  2. Ignoring graph breaks. Silently losing most of the benefit.
  3. Unbounded shape variety, causing recompilation storms (11.j).
  4. Expecting compilation to fix a scheduling problem.
  5. Deploying artifacts built for a different GPU or library version.
  6. Following old TensorRT-LLM guides that tell you to run trtllm-build; current releases have no engine-build step.

10. Hands-on exercise#

  1. Run passes.go. Add a common-subexpression pass: make the graph compute matmul(x, w) twice and merge the duplicates.
  2. Run a small transformer eagerly, with torch.compile, and with mode="max-autotune". Record compile time and per-step time at batch 1 and 64.
  3. Run with TORCH_LOGS="graph_breaks", find a break in some model code, fix it, and measure.
  4. Export the same model with torch.export, compile it with AOTInductor into a .pt2 package, and load it in a fresh process. How long does loading take compared with compiling?
  5. Compare eager and compiled outputs element by element for the same input. How large is the difference? Does it change the greedy next token over 100 prompts?

11. Interview questions#

  1. Name six graph-level optimisations, with an example of each.
  2. Compare AOT and JIT compilation for inference. When would you choose each?
  3. What does each stage of torch.compile do?
  4. What is a graph break, how do you find one, and how do you prevent them in a hot path?
  5. What happens when Dynamo hits its recompile limit, and why is that dangerous in production?
  6. How much of a serving engine’s advantage over eager PyTorch comes from compilation, and how much from scheduling?
  7. How has TensorRT-LLM’s build-and-serve workflow changed?

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