
11 November 2026 · ML System reading notes · 2/6
ML System 02: Compiler Backend and Runtime
Part two is chapter 6 of the book: the compiler backend and the runtime. The frontend hands over a graph that knows nothing about hardware; the backend makes it fast on one specific chip, and the runtime actually runs it. This chapter let me trace the whole path from Python code to the GPU, and I finally get why PyTorch's dynamic graphs are slow and what torch.compile is really doing. It also fixed a wrong idea of mine: I thought CV should use NCHW and LLMs NHWC, and I had both of them wrong.
What the backend optimizes
Every backend optimization targets hardware, and there are two kinds:
- General hardware optimizations look for particular subgraph patterns and swap each one for an equivalent structure that suits the hardware better.
- Chip-specific optimizations depend on the chip's instruction limits and on data layout.
Deep learning operators come in roughly two kinds: compute-bound ones such as matrix multiplication and convolution, and memory-bound ones such as element-wise addition and activation functions. The two almost always sit next to each other, so fusing them into one kernel saves writing the intermediate result to GPU memory and reading it back, which is a big win. The book calls this graph-kernel fusion: split operators apart, then regroup and rebuild them.
Data layout: NCHW or NHWC
An image tensor has four dimensions: N is the batch size, C the channels, H and W the height and width. Layout means the order they are stored in memory. For an RGB image:
- NCHW (PyTorch's default) stores every pixel's R first, then every G, then every B, like three single-color images in a row.
- NHWC (TensorFlow's default) stores one pixel at a time: RGB RGB RGB…
At first I thought you pick by task: convolution in CV must prefer NCHW, and LLMs might prefer NHWC. Both guesses were wrong. The choice depends on the hardware and the kernel, not the task.
Convolution doesn't necessarily prefer NCHW. On modern NVIDIA GPUs, especially with FP16/BF16 on Tensor Cores, NHWC is usually faster. At every position a convolution needs all channels of that pixel together. In NHWC those channels sit next to each other and come out in one contiguous read, which matches how matrix multiplication consumes data.
- PyTorch defaults to NCHW mostly for historical reasons (early cuDNN worked that way). The official advice now is to switch to channels_last, which is NHWC, on GPU:
model = model.to(memory_format=torch.channels_last). - TensorFlow defaults to NHWC because it used to be faster on CPUs.
- Hardware vendors have their own formats too: Intel CPUs (oneDNN) use blocked layouts, and Ascend uses NC1HWC0, which splits C into groups of 16.
LLMs don't have H or W at all. Their tensors are [batch, sequence length, hidden size], or [batch, heads, sequence length, head dim] inside attention, so the NCHW/NHWC question doesn't apply. LLMs have layout problems of their own:
- whether attention uses [B, S, H, D] or [B, H, S, D], since different attention kernels want different ones;
- whether a weight matrix is stored by rows or by columns (transposed or not), which changes how efficiently matrix multiplication reads it;
- how the KV cache is cut into blocks, which is paged KV cache;
- how quantized weights are repacked and interleaved so quantized kernels can read them contiguously.
Who chooses? Usually not you. The framework or compiler backend decides based on the target hardware. It knows which layout the chosen kernel wants and inserts a Transpose into the graph when needed. There are also passes that remove redundant "transpose there and back again" pairs, because every transpose moves all the data once. What you can do is mostly give hints, such as channels_last. TensorRT, NVIDIA's inference compiler, even treats layout as a tuning option at build time and measures it together with everything else to find the fastest combination.
Operator selection and memory allocation
Every operator node needs a concrete implementation, chosen by three things: supported device type, data type and data layout.
Memory comes in two places: device memory on the GPU and host memory on the CPU. The GPU can't access host memory and vice versa, so memory has to be allocated carefully and reused where possible. The usual tools are memory fusion and in-place operators (which write the result straight into the input's memory). Communication operators are often the performance bottleneck.
Scheduling and execution
Scheduling works at two granularities: one operator at a time (single operator scheduling) or the whole graph at once (graph scheduling).
When the operators in one graph run on different devices, it becomes a heterogeneous graph, which is built by partitioning an ordinary graph. There are two ways to do it:
- Subgraph partitioning: subgraphs copy data between them and can run concurrently, but switching between subgraphs costs time.
- Subgraph merging: only operators are copied, there's no switching cost, and operators run concurrently on their own.
The operator compiler
A new operator produced by fusion has no ready-made kernel, so an operator compiler generates one on the spot. TVM and Triton are tools of this kind. The book treats it as the key to getting performance out of hardware, and names two core techniques: optimizing the schedule, and optimization based on the polyhedral model.
What "runtime" means
"Runtime" has two meanings:
- A period of time: when the program is actually running, as opposed to compile time. "A dynamic graph only knows which branch to take at runtime" uses this meaning.
- A piece of software: the manager that actually runs the compiled plan. It allocates and frees GPU memory, launches kernels in graph order, manages streams and synchronization, and moves data in and results out.
The compiler is the director, who writes the script and blocks the scenes in advance. The runtime is the stage manager on the night, calling "lights, entrance, scene change" from the script.
Common runtimes include the CUDA Runtime (cudaMalloc and kernel launches go through it) and TensorRT's runtime (which loads and runs an engine, and is all you need at deployment). The Python interpreter is the runtime for Python code.
The whole path, end to end
Taking a static graph as the example, here is what happens between a piece of PyTorch code and the GPU running it.
- Write Python code in PyTorch.
- PyTorch turns it into a computational graph.
- The graph is translated into IR, a few passes run (such as deleting unused nodes), and the backward graph is derived from the forward graph.
- Everything so far is the frontend, and the result is a first draft of the plan.
- In the backend, the target chip is known, and the graph is reshaped for it: nodes are merged, or split because of hardware limits.
- Each operator node is mapped to a kernel implementation, often from an operator library.
- Choosing a kernel depends on whose GPU it is, the data type, and the data's memory layout. If there's no ready-made kernel (a newly fused node, say), the operator compiler generates one on the spot.
- Memory allocation: from the plan, work out how big each tensor is and when it's last used, and hand its space to later tensors.
- Scheduling: the runtime on the CPU walks the graph in dependency order and does a kernel launch at each node, telling the GPU which kernel to use, that the inputs are at addresses A and B, and to write the result to C. Launches are asynchronous, so the CPU doesn't wait for the GPU to finish. Independent nodes can go on different streams and run in parallel.
- The hardware does the work. The GPU runs kernels in queue order, and each kernel spreads across thousands of threads.
Why dynamic graphs are slow
TensorFlow 1.x was purely static, 2.x switched to dynamic by default, and PyTorch has always been dynamic. Dynamic graphs are easy to debug: for every line of code, the framework picks a kernel and launches it on the spot, then moves to the next line. That flexibility costs speed, for three reasons:
- No fusion, so intermediate results travel in and out of GPU memory far too often.
- Every operator pays a fixed CPU cost: Python interpretation, kernel selection, the launch. Without fusion there are more operators, so more of that cost. When operators are tiny, the GPU finishes faster than the CPU can issue work and sits idle. This is called being launch-bound. Large operators spread the cost thin, so it matters less there.
- No global plan. The framework doesn't know which intermediate results will be needed later, so it keeps more of them and uses more memory. It also doesn't know which operators are independent, so it can't put them on separate streams to run at the same time.
torch.compile
torch.compile turns as much of the dynamic graph as it can into static graphs. Where it can't, you get a graph break, for example at an if that depends on a tensor's actual value.
It has three modes:
| Mode | What it does | When to use it |
|---|---|---|
| default | capture the graph, fuse, generate kernels | most of the time |
| reduce-overhead | default plus CUDA Graphs | when you want to cut launch overhead |
| max-autotune | also spends longer picking the fastest kernels; slowest to compile | deployment |
A CUDA Graph records a whole sequence of kernel launches and replays it in one submission, so the CPU no longer issues them one by one. The fused kernels are generated by Triton.
torch.compile has a frontend and a backend of its own. The frontend, TorchDynamo, captures a static graph (an FX graph) from Python code. The backend is swappable: the default is Inductor (fusion, with kernels generated by Triton), and it can be replaced with TensorRT:
import torch_tensorrt
model = torch.compile(model, backend="tensorrt")
With TensorRT as the backend, Dynamo captures the graph, Torch-TensorRT builds the subgraphs it supports into an engine, unsupported operators fall back to PyTorch, and the two take turns at runtime. It's the same idea as LLVM: frontend and backend are decoupled, so the backend can be swapped freely.