| name | onnxruntime |
| description | Comprehensive reference documentation and skill for ONNX Runtime - the cross-platform high-performance inference and training engine for ONNX models. Covers C/C++ API, Python API (InferenceSession, OrtValue, SessionOptions), all Execution Providers (CUDA, TensorRT, OpenVINO, DNNL, CoreML, NNAPI, WebGPU, DirectML, QNN, etc.), graph optimization pipeline, operator kernel system, shape inference, custom operators, training (ORTModule, TrainingSession), quantization, LoRA adapters, IO Binding, language bindings (C#, Java, JavaScript, Rust, Objective-C), WebAssembly deployment, build system (CMake), MLAS acceleration, mobile deployment, profiling, and plugin development. Based on ONNX Runtime source code analysis.
|
| version | 1.22 |
ONNX Runtime - Cross-Platform Inference & Training Engine
Overview
ONNX Runtime is a cross-platform, high-performance inference and training engine for ONNX (Open Neural Network Exchange) models. It provides optimal performance by leveraging hardware accelerators alongside graph optimizations and transforms. ONNX Runtime supports models from deep learning frameworks such as PyTorch and TensorFlow/Keras, as well as classical ML libraries like scikit-learn, LightGBM, and XGBoost.
Key Capabilities:
- Inference: Accelerate model inference across CPUs, GPUs, NPUs, and edge devices
- Training: Accelerate multi-node GPU training for transformer models with ORTModule
- Quantization: Post-training quantization and quantization-aware training support
- 20+ Execution Providers: Hardware-specific backends for optimal performance
- Cross-Platform: Linux, macOS, Windows, Android, iOS, WebAssembly
Supported Hardware: NVIDIA GPUs (CUDA/TensorRT), AMD GPUs (ROCm/MIGraphX), Intel GPUs (OpenVINO/DNNL), Apple Silicon (CoreML), Qualcomm NPUs (QNN), ARM NPUs (NNAPI), WebGPU, DirectML, and CPU
Supported Languages: C, C++, Python, C#, Java, JavaScript/TypeScript, Rust, Objective-C
ONNX Runtime Version: 1.22
Key Architecture Concepts
- InferenceSession: The primary object for loading and running ONNX models
- Execution Provider (EP): Hardware-specific backend for accelerating operator execution (20+ EPs)
- Graph Optimizer: Multi-level graph transformation pipeline (Level 1-4)
- OpKernel: The base class for operator implementations on specific EPs
- KernelRegistry: Registry mapping (op_type, EP) pairs to kernel implementations
- IExecutionProvider: Interface for all execution providers
- Graph/GraphViewer: IR representation of ONNX models
- OrtValue: Unified tensor/sparse-tensor container
- MLAS: Machine Learning Acceleration System for optimized CPU kernels
- ORT Module: PyTorch-compatible training acceleration module
Architecture Overview
┌─────────────────────────────────────────────────────────────────────┐
│ Language Bindings │
│ Python │ C# │ Java │ JavaScript/TS │ Rust │ Objective-C │ C/C++ │
├──────────────────────┼──────────────────────────────────────────────┤
│ C API (onnxruntime_c_api.h) │
├──────────────────────┼──────────────────────────────────────────────┤
│ InferenceSession / TrainingSession │
├──────────────────────┼──────────────────────────────────────────────┤
│ Graph │ Optimizer │ Partitioning │ Kernel Registry │ Execution │
│ IR │ L1-L4 │ EP Assignment│ │ Scheduling │
├──────────────────────┼──────────────────────────────────────────────┤
│ Execution Providers (20+) │
│ CPU │ CUDA │ TensorRT │ OpenVINO │ DNNL │ CoreML │ NNAPI │ QNN... │
├──────────────────────┼──────────────────────────────────────────────┤
│ MLAS │ Platform │ Memory │ Threading │
└─────────────────────────────────────────────────────────────────────┘
Core Pipeline
Load Model → Parse ONNX → Build Graph IR → Optimize Graph (L1→L2→L3→L4)
↓
Run() ← Execute Kernels ← Assign Kernels ← Partition by EPs
Quick Reference
C++ Inference
#include <onnxruntime_cxx_api.h>
Ort::Env env(ORT_LOGGING_LEVEL_WARNING, "my_app");
Ort::SessionOptions session_options;
session_options.SetIntraOpNumThreads(4);
session_options.SetGraphOptimizationLevel(GraphOptimizationLevel::ORT_ENABLE_ALL);
Ort::Session session(env, L"model.onnx", session_options);
std::vector<int64_t> input_shape = {1, 3, 224, 224};
std::vector<float> input_data(1 * 3 * 224 * 224, 1.0f);
auto memory_info = Ort::MemoryInfo::CreateCpu(OrtArenaAllocator, OrtMemTypeDefault);
auto input_tensor = Ort::Value::CreateTensor<float>(
memory_info, input_data.data(), input_data.size(),
input_shape.data(), input_shape.size());
const char* input_names[] = {"input"};
const char* output_names[] = {"output"};
auto output_tensors = session.Run(Ort::RunOptions{nullptr},
input_names, &input_tensor, 1, output_names, 1);
Python Inference
import onnxruntime as ort
import numpy as np
sess = ort.InferenceSession("model.onnx",
providers=["CUDAExecutionProvider", "CPUExecutionProvider"])
input_data = np.random.randn(1, 3, 224, 224).astype(np.float32)
results = sess.run(None, {"input": input_data})
io_binding = sess.io_binding()
io_binding.bind_cpu_input("input", input_data)
io_binding.bind_output("output")
sess.run_with_iobinding(io_binding)
output = io_binding.copy_outputs_to_cpu()[0]
CUDA Execution Provider
import onnxruntime as ort
providers = [
("CUDAExecutionProvider", {
"device_id": 0,
"arena_extend_strategy": "kNextPowerOfTwo",
"gpu_mem_limit": 2 * 1024 * 1024 * 1024,
"cudnn_conv_algo_search": "EXHAUSTIVE",
"do_copy_in_default_stream": True,
}),
"CPUExecutionProvider",
]
sess = ort.InferenceSession("model.onnx", providers=providers)
Quantization
from onnxruntime.quantization import quantize_dynamic, QuantType
quantize_dynamic("model.onnx", "model_quant.onnx",
weight_type=QuantType.QUInt8)
from onnxruntime.quantization import quantize_static, CalibrationDataReader
quantize_static("model.onnx", "model_quant.onnx",
calibration_data_reader=my_reader)
Session Options
import onnxruntime as ort
opts = ort.SessionOptions()
opts.intra_op_num_threads = 4
opts.inter_op_num_threads = 1
opts.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_ALL
opts.execution_mode = ort.ExecutionMode.ORT_SEQUENTIAL
opts.enable_mem_pattern = True
opts.enable_mem_reuse = True
opts.add_session_config_entry("session.disable_prepacking", "0")
Reference Chapters
Core Architecture
- Overview and Architecture - Design philosophy, system architecture, code layout, core pipeline
- C API Reference - Complete C API functions, types, enums, error handling
- C++ API Reference - C++ wrapper classes, RAII, smart pointers, session management
- Python API - InferenceSession - InferenceSession, model loading, inference execution
- Python API - Configuration - SessionOptions, RunOptions, all config keys
- Python API - OrtValue and Tensors - OrtValue creation, numpy integration, sparse tensors
- Data Types and Memory System - All tensor element types, MemoryInfo, allocators
- Environment and Session Lifecycle - Env creation, session initialization, model loading
- Error Handling and Logging - Status, error codes, logging system, profiling
- Execution Providers Overview - EP architecture, registration, partitioning, fallback
Execution Providers
- CUDA Execution Provider - NVIDIA GPU acceleration, options, kernel implementations
- TensorRT Execution Provider - TensorRT integration, options, trt engine caching
- OpenVINO Execution Provider - Intel hardware acceleration, device selection
- DNNL (oneDNN) Execution Provider - CPU acceleration with oneDNN primitives
- CoreML Execution Provider - Apple Silicon acceleration
- NNAPI Execution Provider - Android NPU acceleration
- WebGPU Execution Provider - GPU acceleration for web via WebGPU
- DirectML Execution Provider - Windows GPU acceleration via DirectML
- QNN and Other Execution Providers - QNN, ACL, CANN, Vitis-AI, XNNPACK, RKNPU, TVM
Graph and Operators
- Graph System Architecture - Graph, GraphViewer, Node, NodeArg, Model classes
- Graph Optimization Passes - All optimizer passes (L1-L4), fusion, elimination, layout transforms
- Operator Kernel System - OpKernel, KernelRegistry, kernel registration, build system
- Shape Inference System - Type/shape inference, op schema, inference context
- Custom Operator Registration - Custom op API, kernel implementation, attribute handling
- Partitioning and Graph Splitting - EP capability, node assignment, data transfer
Training and Optimization
- Training API - ORTModule - ORTModule, TrainingSession, gradient ops, optimizers
- Quantization API - Dynamic/static quantization, calibration, QDQ format
- LoRA Adapter Support - LoRA adapters, dynamic loading, adapter management
- IO Binding and Advanced Inference - IOBinding, pinned memory, zero-copy inference
- Auto Mixed Precision - FP16/BF16 mixed precision, loss scaling
Language Bindings
- C# API Reference - InferenceSession, tensors, providers, async inference
- Java API Reference - OrtSession, OnnxTensor, OnnxValue, provider options
- JavaScript/TypeScript API Reference - InferenceSession, tensors, WebGPU, Node.js/Web
- WebAssembly Deployment - WASM build, web deployment, WebGL/WebGPU
- Rust API Reference - Rust bindings, session, tensor types
- Objective-C API Reference - ORTSession, ORTValue, CoreML integration
Build, Deploy, and Tools
- Build System (CMake) - All CMake options, build targets, cross-compilation
- Docker and Container Deployment - Dockerfiles, container images, deployment
- Profiling and Performance - Profiler, tracing, performance tuning, benchmarking
- Mobile Deployment - Mobile build, NNAPI, CoreML, model optimization
- MLAS Acceleration - Machine Learning Acceleration System, optimized kernels
- Samples and Tutorials - Complete example code for all languages and scenarios
- Plugin Development Guide - EP plugin development, CUDA plugin EP, WebGPU plugin EP
- ONNX Format and Model Loading - ONNX format, ORT format, external data, serialization
- Model Conversion and Optimization Tools - Model optimizer, converter, shape inference tools
- Allocator and Memory Management - Memory patterns, arena allocators, memory planning
- Threading and Parallelism - Thread pools, intra/inter op parallelism, stream handling
- Contributed Operators - Non-standard ops by EP, contrib kernel registration
- CUDA EP Plugin - CUDA EP plugin architecture, kernel patterns, build system
- EP Context and Compiled Models - EP context model, pre-compiled models, weight sharing