Sub topic 11
Avoiding Copies with I/O Binding
Assume you know basic Python, NumPy, PyTorch, and ONNX Runtime sessions. You also need an NVIDIA GPU with a working CUDA execution provider.
Why Copies Matter
A model running on a GPU expects its input in GPU memory. A typical sess.run() call accepts a NumPy array in CPU memory. ONNX Runtime then copies the input to the GPU, runs the model, and copies the output back to CPU memory.
These copies add latency. They also waste bandwidth when a pipeline already keeps images or predictions on the GPU. I/O binding lets you specify where inputs and outputs live.
Binding GPU Inputs and Outputs
Create an OrtValue from the NumPy array and place it on CUDA device zero. Then bind that value as the model input. Binding the output to CUDA keeps the result on the GPU until you explicitly request a CPU copy.
import numpy as np
import onnxruntime as ort
session = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
x_cpu = np.random.rand(8, 3, 224, 224).astype(np.float32)
x_gpu = ort.OrtValue.ortvalue_from_numpy(x_cpu, "cuda", 0)
io = session.io_binding()
io.bind_ortvalue_input("input", x_gpu)
io.bind_output("logits", "cuda", 0)
session.run_with_iobinding(io)
# Keep this output on the GPU for another GPU operation.
logits_gpu = io.get_outputs()[0]
# Copy only when a CPU value is required.
logits_cpu = io.copy_outputs_to_cpu()[0]
print(logits_cpu.shape)bind_output can also let ONNX Runtime allocate the output on the selected device. If the next operation is another GPU operation, use io.get_outputs() rather than copy_outputs_to_cpu().
Common Errors
The input name and output name must match the ONNX graph. Check them with session.get_inputs() and session.get_outputs().
I/O binding does not guarantee that every operation runs on the GPU. A missing CUDA kernel can cause provider fallback to CPU, which may introduce internal transfers. Check the session providers and test the complete graph.
Binding is most useful for large tensors, repeated inference, and pipelines with several GPU stages. For a single small request, the setup cost may outweigh the saved copy.
Exercise
When should you call copyoutputsto_cpu()?
Show answer
Call it only when later code needs a CPU NumPy array. Keep the output as a GPU OrtValue when another GPU operation will consume it.