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
- Environment
- Provider Options
SessionOptions Configuration
Graph Optimization Levels
Optimization Level Details
Optimization Level Details
Higher optimization levels may increase session creation time but improve inference speed. Use
ORT_ENABLE_ALL for production.Execution Modes
Sequential Mode
Parallel Mode
Threading Configuration
ONNX Runtime uses two types of thread pools:- CPU-bound Models
- Complex Graphs
- Single-threaded
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
Verbose Logging
Session Configuration String
Use configuration strings for advanced settings:Memory Management
Memory Arenas
ONNX Runtime uses arena-based memory allocation:Memory Pattern Optimization
Best Practices
Reuse Sessions
Reuse Sessions
Creating a session is expensive. Reuse the same session for multiple inferences:
Thread Safety
Thread Safety
Sessions are thread-safe for inference:
Use IOBinding for Performance
Use IOBinding for Performance
Use IOBinding when running multiple inferences:
Optimize Session Options
Optimize Session Options
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