Sub topic 9
Graph optimization levels and operator fusion
This chapter assumes you can export a model to ONNX and run it in an InferenceSession, as covered in the earlier chapters. You should also know what a node and an operator are in a computation graph. By the end you will be able to choose an optimization level, see what ONNX Runtime changed in your graph, and judge when the setting is worth touching.
What graph optimization does
An exported vision model is a graph of many small operators: Conv, BatchNormalization, Relu, Add, and so on. Running each one separately costs a kernel launch and a pass over memory. The runtime can reduce that work by rewriting the graph before it runs. It never changes what the model computes, only how.
ONNX Runtime applies three kinds of rewrite:
- Constant folding computes any subgraph whose inputs are all constants once, at load time, and stores the result as a new constant.
- Redundant node elimination removes operators that do nothing, such as an
Identityor aDropoutleft over from training. - Operator fusion replaces a chain of nodes with one node that does the same work in a single kernel. A classic case is
Convfollowed byRelu, which becomes one convolution that applies the activation as it writes its output. The intermediate tensor is never written to memory and read back.
Fusion matters most on memory-bound operators. An activation does very little arithmetic per byte it moves, so merging it into the preceding layer removes a full memory round trip.
The optimization levels
You choose how aggressive the rewriting is with graph_optimization_level on SessionOptions.
| Level (Python name) | What it applies | Hardware assumption |
|---|---|---|
| `ORT_DISABLE_ALL` | Nothing | None |
| `ORT_ENABLE_BASIC` | Constant folding, redundant node removal, some simple fusions such as `Conv` + `Add` or `Conv` + `BatchNormalization` | Portable. These rewrites keep standard ONNX operators |
| `ORT_ENABLE_EXTENDED` | Larger fusions, such as `Conv` + activation, `MatMul` + `Add`, GELU, and layer normalization patterns | Fused nodes may use ONNX Runtime's own `com.microsoft` operators, so they depend on the execution provider |
| `ORT_ENABLE_ALL` | Everything above, plus layout changes (for example blocked layouts on the CPU) | Tied to the target hardware |
ORT_ENABLE_ALL is the default, so a plain InferenceSession already optimizes. The exact set of fusions depends on the ONNX Runtime version and on the provider. Treat the table as the general shape, and inspect your own graph, as shown below, before you rely on a particular fusion.
The order matters because of execution providers. Basic rewrites run before the graph is split among providers, so they apply regardless of which provider ends up with a node. Extended and layout rewrites run after the split, and each provider only receives the fusions it has kernels for.
Seeing what changed
You can ask ONNX Runtime to write the optimized graph to disk with optimized_model_filepath. Counting operator types before and after shows exactly which fusions happened. This example uses the resnet50.onnx file from the export chapter, runs on the CPU provider, and needs the onnx package.
from collections import Counter
import onnx
import onnxruntime as ort
LEVELS = {
"disable": ort.GraphOptimizationLevel.ORT_DISABLE_ALL,
"basic": ort.GraphOptimizationLevel.ORT_ENABLE_BASIC,
"extended": ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED,
"all": ort.GraphOptimizationLevel.ORT_ENABLE_ALL,
}
def optimized_op_counts(name, level):
opts = ort.SessionOptions()
opts.graph_optimization_level = level
opts.optimized_model_filepath = f"resnet50_{name}.onnx"
ort.InferenceSession(
"resnet50.onnx",
sess_options=opts,
providers=["CPUExecutionProvider"],
)
graph = onnx.load(opts.optimized_model_filepath).graph
return Counter(node.op_type for node in graph.node)
for name, level in LEVELS.items():
counts = optimized_op_counts(name, level)
print(f"{name:9s} nodes={sum(counts.values()):4d}", dict(counts.most_common(5)))The node count should fall as the level rises, and operator names that were not in your original graph (for example FusedConv) may appear. Those names come from ONNX Runtime's com.microsoft domain and only exist inside ONNX Runtime.
Measuring the effect
Do not assume a higher level is faster for your model. Time each level with the warmup-and-percentile method from the benchmarking chapter. This compact version builds one session per level and reports the median.
import time
import numpy as np
import onnxruntime as ort
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
def median_ms(level, providers, warmup=20, iters=100):
opts = ort.SessionOptions()
opts.graph_optimization_level = level
sess = ort.InferenceSession("resnet50.onnx", sess_options=opts, providers=providers)
feed = {"input": x}
for _ in range(warmup):
sess.run(None, feed)
times = []
for _ in range(iters):
start = time.perf_counter()
sess.run(None, feed)
times.append((time.perf_counter() - start) * 1000.0)
return float(np.median(times))
for name, level in LEVELS.items():
print(name, round(median_ms(level, ["CPUExecutionProvider"]), 2), "ms")On a CPU, disable is usually clearly slower than basic, and all often gains a little more. On a GPU provider, the gap between basic and all is often small for a convolutional network, because the kernels are already efficient. Run the same comparison with your GPU provider list to see your own case.
Saving the optimized model
Optimization costs time when the session is created, and large models can take seconds. If you start many processes with the same model, you can optimize once, save the result, and load it with optimization disabled:
import onnxruntime as ort
opts = ort.SessionOptions()
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.optimized_model_filepath = "resnet50_cpu_opt.onnx"
ort.InferenceSession("resnet50.onnx", sess_options=opts, providers=["CPUExecutionProvider"])
fast_opts = ort.SessionOptions()
fast_opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_DISABLE_ALL
sess = ort.InferenceSession(
"resnet50_cpu_opt.onnx", sess_options=fast_opts, providers=["CPUExecutionProvider"]
)Interaction with TensorRT
When you enable the TensorRT execution provider, ONNX Runtime still applies its basic rewrites, then hands TensorRT the subgraphs it supports. TensorRT performs its own fusion when it builds an engine, so it does not need ONNX Runtime's extended fusions for those subgraphs. Any nodes TensorRT rejects fall back to the CUDA or CPU provider and still benefit from the higher levels. The next chapters cover this in detail.
Common errors
- Comparing a saved optimized model with the original and finding different operators. This is expected. Check parity on outputs, not on graph structure.
- Loading a saved optimized file on different hardware. It may fail with an unsupported operator error, or silently run slower. Re-export from the original file.
- Turning off optimization to debug.
ORT_DISABLE_ALLis useful when you suspect a fusion bug. If the outputs change between levels beyond normal floating-point tolerance, report it and run the parity check from the earlier chapter at each level. - Expecting fusion to fix a slow model. If the time goes to host-device copies or preprocessing, no graph rewrite will help.
Exercise
You save an optimized model at ORTENABLEALL using the CPUExecutionProvider, then deploy that file to a GPU server using the CUDAExecutionProvider. What could go wrong, and what should you ship instead?
Show answer
The saved file contains fused nodes chosen for the CPU, which can include com.microsoft operators and layout changes that the CUDA provider has no kernels for. The session may fail to load or run those nodes on the CPU. Ship the original, unoptimized resnet50.onnx and let ONNX Runtime optimize it on the target machine, or generate a separate optimized file on the GPU machine itself.
Exercise
Why does ONNX Runtime apply basic optimizations before partitioning the graph among execution providers, but extended optimizations after?
Show answer
Basic rewrites such as constant folding and redundant node removal use standard ONNX operators, so they are valid for every provider. Extended fusions produce nodes that only some providers implement, so they can only be chosen once the graph has been assigned to a provider.