Sub topic 11
Avoiding copies with I/O binding
This chapter assumes you can export a model to ONNX, create an InferenceSession, and select the CUDA execution provider. It also assumes you know that a GPU has its own memory, separate from host (CPU) memory. If you do not, review the earlier chapters on sessions and execution providers first.
Why `run` copies data
When you call sess.run(None, {"input": x}) with a NumPy array, ONNX Runtime does several things for you:
- It copies
xfrom host memory to GPU memory. - It runs the graph on the GPU.
- It copies each output from GPU memory back to host memory and returns NumPy arrays.
This is convenient, and for a small model on a slow path it is fine. For a fast GPU model, the two copies can take a large share of the total time. The copies also cross the PCIe bus, which is much slower than GPU memory bandwidth.
I/O binding lets you take control of where inputs and outputs live. If the input is already on the GPU, for example because a preprocessing step produced it there, you can skip the upload. If the next step also runs on the GPU, you can skip the download.
The pieces: OrtValue and IOBinding
Two objects matter here.
OrtValueis ONNX Runtime's own tensor container. It can hold data on the CPU or on a CUDA device.IOBindingis an object created from a session. You attach inputs and outputs to it by name, then run the session against the binding.
The following example uploads one batch once, binds it, and lets ONNX Runtime allocate the output on the GPU. It assumes sess is the CUDA-enabled session from earlier.
import numpy as np
import onnxruntime as ort
sess = ort.InferenceSession(
"resnet50.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)
x = np.random.rand(8, 3, 224, 224).astype(np.float32)
x_gpu = ort.OrtValue.ortvalue_from_numpy(x, "cuda", 0)
io = sess.io_binding()
io.bind_ortvalue_input("input", x_gpu)
io.bind_output("logits", "cuda", 0)
sess.run_with_iobinding(io)
logits = io.copy_outputs_to_cpu()[0]
print(logits.shape)Walking through it:
ortvalue_from_numpy(x, "cuda", 0)copies the array to device 0 once. After that,x_gpulives on the GPU.bind_ortvalue_inputattaches that GPU tensor to the input namedinput. The name must match the name you gave at export time.bind_output("logits", "cuda", 0)tells ONNX Runtime to allocate the output on GPU 0. You do not supply a buffer, so the runtime sizes it from the result.run_with_iobindingruns the graph. No host-device copies happen inside this call.copy_outputs_to_cpu()is an explicit download. You only call it when you need the values on the host.
The copy has not disappeared. It has moved from a hidden step inside run to an explicit step you can choose to skip or batch.
Keeping the output on the GPU
If a postprocessing step such as softmax or non-maximum suppression runs on the GPU, you do not want to download the logits at all. Use io.get_outputs() to get the output as an OrtValue that still lives on the device.
out_ort = io.get_outputs()[0]
print(out_ort.device_name(), out_ort.shape())You can pass the device pointer to another library through out_ort.data_ptr(). This is useful for sharing memory with CUDA-aware code, but you must keep the OrtValue alive for as long as the other code reads from that pointer. If the OrtValue is garbage collected, the memory is freed.
Reusing buffers across calls
Allocating a fresh output on every call costs time. In a serving loop you can preallocate the output once and bind it each time. The output shape must match what the model will produce, so this works best with a fixed batch size.
batch = 8
out_np = np.zeros((batch, 1000), dtype=np.float32)
out_gpu = ort.OrtValue.ortvalue_from_numpy(out_np, "cuda", 0)
io = sess.io_binding()
io.bind_ortvalue_output("logits", out_gpu)
for _ in range(100):
# Overwrite the GPU input in place instead of making a new one.
x_gpu.update_inplace(np.random.rand(batch, 3, 224, 224).astype(np.float32))
io.bind_ortvalue_input("input", x_gpu)
sess.run_with_iobinding(io)update_inplace copies new host data into the existing GPU buffer, so the device address stays the same. In a real pipeline you would fill that buffer from a GPU preprocessing kernel instead of from NumPy.
Binding memory you already own
Sometimes the data is not in an OrtValue at all. A PyTorch CUDA tensor is a common case. You can bind its memory directly with bind_input, giving the device type, device id, element type, shape, and raw pointer.
import torch
t = torch.rand(8, 3, 224, 224, device="cuda", dtype=torch.float32).contiguous()
io = sess.io_binding()
io.bind_input(
name="input",
device_type="cuda",
device_id=0,
element_type=np.float32,
shape=tuple(t.shape),
buffer_ptr=t.data_ptr(),
)
io.bind_output("logits", "cuda", 0)
sess.run_with_iobinding(io)Here ONNX Runtime reads straight from the PyTorch tensor with no copy. Two conditions must hold:
- The tensor must be contiguous and must have the dtype and shape you declare. A mismatch produces wrong results or an error.
- The tensor must stay alive until the run finishes. Keep a reference to
tuntil you have consumed the output.
Common errors and gotchas
- Binding to a device the session does not use. If the session fell back to the CPU provider, a CUDA binding can fail or cause an implicit copy. Print
sess.get_providers()and confirm CUDA is first. - Wrong input or output name. Names come from the exported graph. Check them with
[i.name for i in sess.get_inputs()]and[o.name for o in sess.get_outputs()]. - Dtype mismatches. Float64 NumPy arrays are the usual cause. Cast with
.astype(np.float32)before upload. - Stale bindings. A binding keeps its previous inputs and outputs. If the input shape changes, rebind the input. Call
io.clear_binding_inputs()andio.clear_binding_outputs()when you want a clean slate. - Sharing one binding across threads. An
IOBindingholds state. Create one per thread or per worker, or protect it with a lock. - Stream synchronization with other libraries. When another library writes the input on its own CUDA stream, make sure its work is finished before you call
run_with_iobinding. Otherwise the model can read half-written data. Synchronizing the other stream first is the simple fix.
When it helps and when it does not
I/O binding pays off when these hold:
- The model is fast, so copy time is a large fraction of total time.
- Inputs are large, such as big batches or high-resolution images.
- Pre- and postprocessing can run on the GPU, so data never needs to visit the host.
It helps little when the model is slow compared with the copies, or when your data starts on the CPU and must be uploaded anyway. In that second case, you still save the output download if later steps run on the GPU, and you can overlap uploads with compute by using separate streams, which is outside this chapter.
The same binding API works with the TensorRT execution provider, since it also uses device memory. Check with sess.get_providers() that the provider you expect is the one running.
Exercise
A colleague's service calls sess.run(None, {"input": x}) on a CUDA session, where x is a NumPy batch. Profiling shows large time spent in host-to-device and device-to-host copies, although the postprocessing (softmax and top-k) could run on the GPU. Which changes would you make with I/O binding, and what must you keep alive?
Show answer
Upload the batch to an OrtValue (or bind a CUDA tensor that preprocessing already produced) and use bindortvalueinput. Bind the output to "cuda" with bindoutput, or preallocate an output OrtValue and bind it with bindortvalueoutput, then call runwithiobinding. Take the output as a device OrtValue with getoutputs() and pass its data_ptr() to the GPU postprocessing, so logits are never downloaded. Download only the small final result (the top-k indices) when needed. Keep the input and output OrtValues, and any PyTorch tensor whose pointer you bound, alive until the run and the downstream reads finish. Also synchronize any other CUDA stream that wrote the input before the run.
Exercise
You bind a preallocated output of shape (8, 1000), then a request arrives with a batch of 5. What goes wrong, and how do you handle it?
Show answer
The bound output buffer no longer matches the shape the model produces, so the run can fail or the output is read incorrectly. Either let ONNX Runtime allocate the output with bind_output for variable batch sizes, or keep one preallocated output per batch size you support, or pad the batch to 8 and discard the extra rows.