Pidoku

Computational Graphs and Operators

Module 11 Lesson 11.b 1h Difficulty 2/5

Prerequisites 11.a, 10.i


Before you start: words you need#

WordPlain meaning
GraphBoxes joined by arrows. Here the boxes are operations and the arrows are the tensors passed between them.
DAGDirected acyclic graph: every arrow points one way and nothing loops back.
Operator (op)A named computation with fixed rules, such as MatMul or Softmax. It says what is computed.
KernelA GPU program that computes one or more operators for a given device, data type and shape. It says how.
Eager modeRunning each operator the moment the Python line is reached, one kernel at a time.
TracingRunning the model once while recording the operators it calls, to build the graph.
Graph breakA point the tracer cannot follow, which splits the graph into separate pieces.
DispatchThe CPU work that picks and launches the right kernel for an operator.

1. What is it?#

A model is a directed acyclic graph: nodes are operators (matmul, add, softmax) and edges are tensors. Inference executes that graph in an order where every node runs after its inputs are ready.

flowchart TB
  X["x"] --> M1["MatMul"]
  W1["w1"] --> M1
  M1 --> A["Add"]
  B1["b1"] --> A
  A --> S["SiLU"]
  S --> M2["MatMul"]
  W2["w2"] --> M2
  M2 --> O["out"]
  class M1,M2,A,S compute
  class W1,W2,B1 memory
  class X,O neutral

An operator is the “what”: MatMul, Softmax, RMSNorm. A kernel is the “how”: one concrete GPU program for one device, data type and range of shapes. One operator can have dozens of kernels; one kernel can also cover several operators fused together (11.h).


2. Why does it exist?#

Because a graph is a program you can study before you run it. A transformer’s forward pass has almost no decisions that depend on the data (1.a): the same operators run in the same order for every input. So a system can, ahead of time:

  • plan exactly where every tensor lives in memory, and reuse buffers;
  • fuse neighbouring operators into one kernel;
  • remove or reorder work that does not change the result;
  • pick the best kernel for each shape;
  • compile the whole thing once.

None of that is possible for an arbitrary program. It is possible here, and it is the basis of torch.compile, TensorRT, ONNX Runtime, XLA and TVM (11.i).


3. Simple analogy#

A recipe drawn as a flowchart. “Chop onions” and “heat oil” do not depend on each other, so they can happen in either order or at once. “Fry onions” needs both. A cook who sees the dependencies, not just a numbered list, can do independent steps together, use one pan for compatible steps and skip washing up in between. That is what a graph compiler does with operators.


4. Tiny example: build a graph and plan its memory#

The program builds the four-operator graph from section 1, prints it, and does the first thing a compiler does with a graph: works out the last use of each intermediate tensor. After its last use, a tensor’s memory can be handed to the next one.

Go
// graph.go — a tiny model as a graph of operators, plus the first thing a
// compiler does with it: work out when each intermediate tensor can be freed.
package main

import (
	"fmt"
	"strings"
)

type Node struct {
	Name   string
	Op     string // "input", "matmul", "add", "silu", ...
	Inputs []*Node
}

type Graph struct{ Nodes []*Node }

func (g *Graph) Add(name, op string, inputs ...*Node) *Node {
	n := &Node{name, op, inputs}
	g.Nodes = append(g.Nodes, n)
	return n
}

func main() {
	// h = silu(x·w1 + b1);  out = h·w2
	g := &Graph{}
	x, w1, b1, w2 := g.Add("x", "input"), g.Add("w1", "input"), g.Add("b1", "input"), g.Add("w2", "input")
	h := g.Add("h0", "matmul", x, w1)
	h = g.Add("h1", "add", h, b1)
	h = g.Add("h2", "silu", h)
	g.Add("out", "matmul", h, w2)

	// Live ranges: the last step at which each value is read.
	lastUse := map[*Node]int{}
	for step, n := range g.Nodes {
		for _, in := range n.Inputs {
			lastUse[in] = step
		}
	}
	for step, n := range g.Nodes {
		var in []string
		for _, i := range n.Inputs {
			in = append(in, "%"+i.Name)
		}
		line := fmt.Sprintf("%%%-4s = %s(%s)", n.Name, n.Op, strings.Join(in, ", "))
		var free []string
		for _, i := range n.Inputs {
			if lastUse[i] == step && i.Op != "input" {
				free = append(free, "%"+i.Name)
			}
		}
		if len(free) > 0 {
			line = fmt.Sprintf("%-26s ; last use of %s, its buffer can be reused", line, strings.Join(free, ", "))
		}
		fmt.Println(line)
	}
}

Output:

%x    = input()
%w1   = input()
%b1   = input()
%w2   = input()
%h0   = matmul(%x, %w1)
%h1   = add(%h0, %b1)      ; last use of %h0, its buffer can be reused
%h2   = silu(%h1)          ; last use of %h1, its buffer can be reused
%out  = matmul(%h2, %w2)   ; last use of %h2, its buffer can be reused

Three intermediates, but never more than two alive at once, so two buffers are enough. PyTorch builds this same structure for you: torch.fx.symbolic_trace(model).graph prints something that looks almost identical.

Notice also that matmul → add → silu are three operators. Run eagerly, they are three kernels and three round trips to GPU memory for the intermediates. A compiler can fold the add and silu into the matmul’s final step and make it one kernel (11.h).


5. Technical explanation#

The operator set of an LLM#

It is surprisingly small. A dense model like Qwen3-8B or Llama 3 uses about a dozen:

Embedding (gather)        look up one row per token
MatMul / Linear           almost all the FLOPs
RMSNorm                   a reduction, then elementwise scaling      11.e
SiLU, GELU                elementwise activations                    10.e
Mul, Add                  gating and residual connections
RoPE                      elementwise rotation with sin/cos tables
Attention                 matmul, scale, mask, softmax, matmul       11.f
Softmax                   a reduction, then elementwise
TopK, sort, sample        choosing the next token                    12.o
Cast                      change of number format
Reshape, transpose, view  usually metadata only, no data moved       11.g
KV cache write            scatter new K and V into the cache         12.l

2026 models add a handful more:

Router + top-k + grouped GEMM   mixture-of-experts layers (14.g)
QK-norm                         RMSNorm on each query and key head (Qwen3, Gemma 3)
Short causal conv1d + gated     linear-attention layers in hybrid models such as
  delta-rule scan               Qwen3-Next and Qwen3.5 (11.d)
Attention sinks, sliding window variants of the attention mask (gpt-oss, Gemma 3)

A small operator set is why a working inference engine is a realistic project, and why a new accelerator can run LLMs with a modest kernel library.

Graph representations you will meet#

SystemWhat the graph isWhen it is built
PyTorch eagerno graph: each op dispatched as Python reaches itnever
torch.fxa Python-level graph of callsby symbolic tracing
torch.compile (Dynamo + Inductor)FX graphs captured from Python bytecode, lowered to Triton or C++on first call, then cached
torch.exportone whole-program graph, with no Python left in itahead of time
ONNXa serialised graph in a standard file formatat export
TensorRTan optimised “engine” binary for one GPU typeat build time
XLA (StableHLO)the graph format used by JAX and TPUstrace, then compile
Apache TVM (Relax)an IR plus schedulesat compile time

TorchScript, PyTorch’s older graph format, was deprecated in PyTorch 2.10; torch.export is its replacement. TensorRT-LLM has also moved away from building TensorRT engines: it now runs on PyTorch, and its engine backend has been removed (11.i).

Static and dynamic graphs#

Static (define, then run):   build the whole graph, then run it many times
    + full optimisation, exact memory plan, ahead-of-time compilation
    - shapes must be known or bucketed (11.j); control flow is awkward

Dynamic (define by running): run ops as the Python executes
    + easy to write and debug; any control flow
    - per-op dispatch cost; no optimisation across ops

PyTorch is dynamic by default. torch.compile captures static pieces where it can and drops back to eager at graph breaks (11.i).

What the graph makes possible#

  1. Memory planning. Section 4 in miniature: tensors whose lifetimes do not overlap share a buffer. Peak memory becomes “the most alive at once”, not “the sum of all”.
  2. Constant folding. scale = 1/sqrt(head_dim) is computed once at build time.
  3. Dead code elimination. Dropout in inference mode, unused outputs, debug branches: gone.
  4. Layout choice. Pick tensor layouts for the whole graph so the fewest transposes are needed (11.g).
  5. Kernel selection. For each matmul shape, choose the best kernel, sometimes by timing candidates during the build.

6. Under the hood: what eager mode costs#

How PyTorch eager mode runs one x @ w:

Python:  x @ w → Tensor.__matmul__ → torch.matmul
C++:     dispatcher looks up (operator, device, dtype, layout)
         autograd layer (skipped under torch.inference_mode())
         CUDA implementation → cuBLAS chooses a GEMM kernel
Driver:  cudaLaunchKernel (5.d)

That is a few microseconds to around ten microseconds of CPU time per operator, before the GPU does anything. With a few hundred operators per decode step (11.a), it adds up to a millisecond or more per token.

A captured graph removes most of this: one Python call runs a pre-built sequence of launches, and a CUDA graph (5.f) turns that sequence into a single launch.


7. Performance implications#

  • Eager mode pays dispatch per operator. At small batch, when each kernel is short, this can be a large share of the step.
  • A captured graph is what makes CUDA graphs possible, which remove almost all of it.
  • Fusion opportunities only exist at the graph level. A system that sees one operator at a time cannot fuse.
  • Memory planning lowers peak activation memory, which is memory you can give to the KV cache instead.

8. Production implications#

  • Serve from a captured or compiled path. vLLM captures CUDA graphs and uses torch.compile by default (18.d), SGLang captures CUDA graphs by default; eager mode is for development and debugging.
  • Compilation takes time and must be cached. Key the cache by model, GPU type, shapes and library versions, and build it into the image or keep it on persistent storage (3.g), so a restart does not recompile.
  • Watch for graph breaks in any model code you write. One unsupported Python construct in the hot path splits the graph. TORCH_LOGS="graph_breaks" python ... lists them.
  • Dynamic shapes are the central difficulty of compiling LLMs (11.j).

9. Common mistakes#

  1. Assuming eager and compiled results are bit-identical. Fusion changes the order of floating-point operations, so results differ slightly, and after sampling the text can differ (11.k).
  2. Compiling at startup in production without a cache. Minutes of cold start on every restart.
  3. Putting print() or .item() in the forward pass. Each one is a graph break.
  4. Building a TensorRT engine on one GPU type and deploying it on another. Engines are tied to the GPU architecture they were built for.
  5. Confusing operators with kernels. “Attention is slow” is about an operator; the fix is usually choosing a different kernel for it.

10. Hands-on exercise#

  1. Run graph.go. Add a residual connection, out2 = add(out, x), and see how the last-use column changes.
  2. Use torch.fx.symbolic_trace on a small transformer block. Print the graph and count the operators by type. How many are matmuls and how many elementwise?
  3. Time one forward pass with torch.profiler, separating CPU time from GPU time. What fraction is dispatch at batch 1, and at batch 64?
  4. Compile the same block with torch.compile. Measure the speedup at batch 1 and batch 64, and explain why they differ.
  5. Add print(x.sum().item()) inside the forward pass, run with TORCH_LOGS="graph_breaks", and measure what the break costs.
  6. Export the block to ONNX and open it in Netron. Compare its operator list with section 5.

11. Interview questions#

  1. What is a computational graph, and why does having one enable optimisation?
  2. What is the difference between an operator and a kernel?
  3. Name four optimisations that need graph-level visibility.
  4. What is a graph break in torch.compile, and why does it matter?
  5. Why does eager-mode overhead hurt more at batch 1 than at batch 256?
  6. Why must a TensorRT engine be rebuilt for each GPU architecture?

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