Skip to main content
The InferenceSession is the primary interface for running ONNX models in ONNX Runtime. It manages model loading, optimization, initialization, and execution.

Session Lifecycle

Understanding the session lifecycle is crucial for optimal performance:
1

Creation

Session object is instantiated with options
2

Model Loading

ONNX model is parsed and internal graph is built
3

Optimization

Graph transformations are applied based on optimization level
4

Partitioning

Graph is partitioned across execution providers
5

Initialization

Kernels are instantiated and memory is pre-allocated
6

Execution

Multiple inferences can be run efficiently

Creating Sessions

Basic Session Creation

Advanced Session Configuration

SessionOptions Configuration

Graph Optimization Levels

Higher optimization levels may increase session creation time but improve inference speed. Use ORT_ENABLE_ALL for production.

Execution Modes

Sequential Mode

Operators execute one after another. Lower memory usage, simpler debugging.

Parallel Mode

Independent operators execute in parallel. Better throughput, higher memory usage.

Threading Configuration

ONNX Runtime uses two types of thread pools:
Setting too many threads can hurt performance due to context switching and cache contention. Start with the number of physical cores.

Running Inference

Basic Inference

Multiple Inputs and Outputs

Using RunOptions

Model Metadata

Inspecting Session Information

Dynamic Input Shapes

Handle models with dynamic dimensions:

IOBinding for Advanced Usage

IOBinding provides fine-grained control over memory and device placement:

Basic IOBinding

GPU Memory Binding

Pre-allocated Output

Profiling and Debugging

Enable Profiling

View the profiling JSON file in Chrome’s tracing viewer (chrome://tracing) for detailed performance analysis.

Verbose Logging

Session Configuration String

Use configuration strings for advanced settings:

Memory Management

Memory Arenas

ONNX Runtime uses arena-based memory allocation:
Disabling memory arenas may increase memory allocation overhead. Only disable for debugging or when you need deterministic memory usage.

Memory Pattern Optimization

Best Practices

Creating a session is expensive. Reuse the same session for multiple inferences:
Sessions are thread-safe for inference:
Use IOBinding when running multiple inferences:
Tune session options for your use case:

Next Steps

Graph Optimizations

Learn about optimization techniques that improve performance

Execution Providers

Understand hardware acceleration options

Performance Tuning

Optimize inference performance for production

Performance Tuning

Improve throughput with performance tuning