Skip to main content

Python Inference API

Learn how to run ONNX model inference in Python using the ONNX Runtime API. This guide includes real API signatures and working code examples.

Installation

Quick Start

Here’s a minimal example to run inference:

InferenceSession Class

Creating a Session

From file path:
From bytes:
With session options:

Session Methods

run()

Execute the model with input data.
Complete example:

get_inputs()

Get model input metadata.

get_outputs()

Get model output metadata.

get_modelmeta()

Get model metadata.

SessionOptions

Configure session behavior before creating the session.

Graph Optimization Levels

RunOptions

Configure individual inference runs.

Execution Providers

Checking Available Providers

Setting Providers

Priority order:
With provider options:
Check active provider:

Common Providers

Working with IOBinding

Use IOBinding for zero-copy inference with GPU tensors.

Complete Example: Image Classification

Performance Tips

Always specify execution providers in priority order. GPU providers like CUDA or TensorRT can provide 10-100x speedups for compute-intensive models.
Set graph_optimization_level to ORT_ENABLE_ALL for maximum performance. The runtime will fuse operators and optimize the graph.
Creating a session is expensive. Create once and reuse for multiple inferences.
When using GPU providers, IOBinding eliminates CPU-GPU memory copies for better performance.
Process multiple inputs in a single batch when possible to maximize hardware utilization.

Error Handling

Next Steps

Model Optimization

Learn how to optimize models for production

Execution Providers

Configure hardware acceleration