Sub topic 4
Running the model with ONNX Runtime
This chapter assumes you have exported resnet50.onnx as shown in the previous chapter, with an input named input, an output named logits, and a dynamic batch axis. You should be comfortable with NumPy arrays and dtypes. The GPU parts need an NVIDIA GPU, but everything here also runs on the CPU.
What ONNX Runtime does with your file
ONNX Runtime (ORT) is an inference engine. It loads an ONNX graph, optimizes it, splits it among backends called execution providers, and runs it. The object that holds all of this is InferenceSession.
Creating a session is the expensive step. ORT parses the file, runs graph optimizations, assigns each node to a provider, and allocates memory. Calling run is the cheap step you repeat. Build the session once at process start and reuse it for every request.
Installing the right package
ORT ships as separate pip packages. onnxruntime is CPU only. onnxruntime-gpu includes the CUDA and TensorRT providers. Install one of them, not both. When both are present they share the same Python module directory, and the CPU build can shadow the GPU build. This is a common cause of a session that silently runs on the CPU.
pip install onnxruntime-gpu numpyThe GPU package also needs matching CUDA and cuDNN libraries on the machine. Check the ORT compatibility table for your version.
Creating a session and choosing providers
The providers list is ordered by priority. ORT gives each graph node to the first provider that supports it, and the CPU provider catches the rest.
import numpy as np
import onnxruntime as ort
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
print(sess.get_providers())
x = np.random.rand(1, 3, 224, 224).astype(np.float32)
logits = sess.run(None, {"input": x})[0]
print(logits.shape)Always print sess.get_providers(). It returns the providers the session actually registered. If CUDA could not load, because the library is missing or the wrong package is installed, ORT logs a warning and the list contains only CPUExecutionProvider. The model still runs, so the failure is easy to miss. You can also call ort.get_available_providers() to see what the installed build supports.
A provider listed in the session does not mean every node runs on it. Unsupported operators fall back to the CPU, and each switch between devices costs a memory copy. Later chapters cover this fallback in detail.
Inspecting the model's inputs and outputs
Do not hard-code names from memory. Read them from the session.
for i in sess.get_inputs():
print("input", i.name, i.shape, i.type)
for o in sess.get_outputs():
print("output", o.name, o.shape, o.type)For the exported ResNet-50 this prints something like input input ['batch', 3, 224, 224] tensor(float). Three details matter:
- The
shapelist mixes integers and strings. A string such as'batch'is a dynamic axis, so any size is accepted there. typeis the ONNX element type.tensor(float)means float32,tensor(float16)means float16, andtensor(double)means float64.nameis the key you use in the feed dictionary.
Calling run
The signature is sess.run(output_names, input_feed).
output_namesis a list of output names to return, orNonefor all outputs. Requesting only the outputs you need can avoid copying the others back to the host.input_feedis a dictionary from input name to NumPy array.- The return value is a list of NumPy arrays, in the order of
output_names. That is why the examples index[0].
name_in = sess.get_inputs()[0].name
name_out = sess.get_outputs()[0].name
batch = np.random.rand(4, 3, 224, 224).astype(np.float32)
(logits,) = sess.run([name_out], {name_in: batch})
print(logits.shape) # (4, 1000)Because the batch axis is dynamic, the same session accepts batch sizes 1 and 4 without reloading. Axes that you exported as fixed do not. Passing a different size raises an error.
Session options
SessionOptions controls behavior that applies to the whole session. Set it before you create the session.
import onnxruntime as ort
opts = ort.SessionOptions()
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.intra_op_num_threads = 4
opts.log_severity_level = 2 # 0 verbose, 1 info, 2 warning, 3 error, 4 fatal
sess = ort.InferenceSession(
"resnet50.onnx",
sess_options=opts,
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)| Option | Effect | Typical use |
|---|---|---|
| `graph_optimization_level` | How aggressively ORT rewrites the graph. The default is already `ORT_ENABLE_ALL`. | Lower it only to debug a suspected optimizer bug. |
| `intra_op_num_threads` | Threads used inside one operator on the CPU. | Match the physical cores you can spare. |
| `log_severity_level` | Verbosity of ORT's own logging. | Set to 0 or 1 to see which provider took which node. |
| `enable_profiling` | Writes a JSON trace of per-node timings. | Find slow operators. |
With the CUDA provider, CPU thread settings matter less, because the heavy work runs on the GPU. They still affect any nodes that fell back to the CPU.
Common errors
Most first-run failures come from a mismatch between the feed and the model's declared inputs.
| Symptom | Cause | Fix |
|---|---|---|
| Error about an invalid feed input name | The dictionary key differs from the ONNX input name. | Use `get_inputs()[0].name`. |
| Error about unexpected input data type, actual `double`, expected `float` | NumPy defaults to float64, for example from `np.random.rand`. | Call `.astype(np.float32)`. |
| Error about invalid dimensions for input | A fixed axis does not match, or the rank is wrong, such as HWC data fed to an NCHW model. | Compare with `get_inputs()[0].shape` and transpose. |
| `get_providers()` shows only the CPU | GPU package not installed, CPU package shadowing it, or CUDA libraries not found. | Reinstall one package and check the library paths. |
| Output differs slightly from PyTorch | Fused kernels change floating-point rounding. | Compare with a tolerance, covered in the parity chapter. |
Passing a non-contiguous array
ORT copies the data it needs, but it expects a standard dense layout. A transposed view such as img.transpose(2, 0, 1) is not contiguous in memory. ORT handles it, but the copy is hidden. Make it explicit with np.ascontiguousarray(...) so you know where the cost occurs.
hwc = np.random.rand(224, 224, 3).astype(np.float32)
chw = np.ascontiguousarray(hwc.transpose(2, 0, 1))[None] # shape (1, 3, 224, 224)
out = sess.run(None, {"input": chw})[0]
print(out.shape)Summary of the working model
- Create one
InferenceSessionper model per process, with an explicit ordered provider list. - Verify the active providers with
get_providers(). - Read input names, shapes, and types from the session.
- Feed float32 NumPy arrays in NCHW layout, matching the declared type.
- Treat the returned list of arrays as the outputs, in order.
Exercise
You run a session created with providers=["CUDAExecutionProvider", "CPUExecutionProvider"] on a machine where the CUDA libraries fail to load. The script prints correct logits but runs slowly. What do you check first, and how do you confirm the cause?
Show answer
Print sess.getproviders(). If it returns only ["CPUExecutionProvider"], the CUDA provider failed to register and ORT fell back to the CPU without raising an error. Then check that onnxruntime-gpu is installed (and the CPU-only onnxruntime package is not shadowing it) and that the CUDA and cuDNN versions match the ORT release. Setting logseverity_level to 0 or 1 shows the provider load error.
Exercise
Your feed is {"input": np.random.rand(1, 3, 224, 224)} and the call fails with a data type error. Why, and what is the one-line fix?
Show answer
np.random.rand returns float64, but the model input is tensor(float), which is float32. Add .astype(np.float32) to the array before calling run.