Overview

5 Exploring ONNX

The text introduces ONNX as an open standard for machine learning interoperability, emphasizing its role in making models portable across frameworks, hardware platforms, and deployment environments. It explains that ONNX consists of a common model format and a runtime system, allowing trained models from frameworks such as PyTorch, TensorFlow, Keras, and others to be converted, optimized, quantized, and executed consistently. A key idea is that ONNX helps avoid framework or hardware lock-in by representing models as directed computational graphs composed of typed tensors and operators.

The text then explains how ONNX models are built and executed. Operators such as matrix multiplication, addition, reshaping, softmax, normalization, and quantization form the basic building blocks of ONNX graphs, while strong typing and tensor shapes define the inputs and outputs of each operation. A simple linear regression example shows how to construct a model graph programmatically, validate it, serialize it, reload it, and inspect its structure. The ONNX Runtime is presented as the production-oriented execution engine, supporting inference sessions, input and output handling, and hardware-specific execution providers for CPUs, GPUs, mobile devices, edge platforms, and specialized accelerators.

The text concludes by applying ONNX to language models, showing how transformer-based models such as BERT and GPT-2 can be exported from PyTorch, validated, optimized, and run through ONNX Runtime on both CPU and GPU. It highlights practical performance benefits, including faster CPU inference after conversion and additional gains from transformer-specific graph optimization. For GPU deployments, it explains the importance of choosing the correct execution provider and reducing unnecessary CPU-GPU data transfers through I/O binding. Overall, ONNX is presented as a central tool for making small and large language models more portable, efficient, and deployment-ready across diverse environments.

ONNX overview.
The list of organizations supporting the ONNX initiative.
All the possible operations on ML/DL models in ONNX.
Visualization of a Linear Regression model implemented in ONNX using the Netron library.
The ONNX Runtime execution model.
Part of ONNX graph of the BERT uncased converted model (one attention block only)

Summary

  • ONNX provides an open standard format for machine learning model interoperability across different frameworks and hardware platforms.
  • ONNX runtime enables efficient execution of ONNX models on various hardware configurations including CPUs, GPUs, and edge devices.
  • ONNX operators define the basic building blocks that describe virtually any machine learning model from various frameworks.
  • ONNX supports multiple data types including float32, int8, int16, int32, int64, and specialized formats like bfloat16.
  • ONNX runtime execution providers optimize model performance by leveraging specific hardware capabilities like CUDA for NVIDIA GPUs.
  • Model optimization in ONNX can be performed offline during conversion or online during inference session initialization.
  • Graph optimization levels in ONNX range from basic constant folding to extended node fusions and layout transformations.
  • IOBinding in ONNX runtime eliminates data copying between CPU and GPU by keeping data on the target execution device.
  • ONNX converted models typically achieve faster inference times compared to their original framework implementations.
  • Validation of ONNX models requires checking both schema consistency and numerical output equivalence with original models.
  • ONNX runtime supports multiple programming language bindings but Python provides the most comprehensive API access.
  • ONNX models can be optimized specifically for transformer architectures using the onnxruntime.transformers.optimizer module.
  • Converting language models to ONNX format preserves model functionality while enabling deployment across diverse production environments.

FAQ

What is ONNX and why is it important for machine learning interoperability?ONNX stands for Open Neural Network Exchange. It is an open standard for ML/DL interoperability that defines a common model format and a common set of operators. Its main value is portability: models trained in frameworks such as PyTorch, TensorFlow, Keras, Scikit-Learn, XGBoost, and others can be converted to ONNX and then deployed across different runtimes, hardware vendors, and accelerators without being locked into one framework or platform.
What are the two main parts of the ONNX ecosystem?ONNX consists mainly of two projects: the ONNX format and the ONNX Runtime. The ONNX format defines how models are represented, including graphs, tensors, operators, inputs, outputs, and metadata. ONNX Runtime, often abbreviated as ORT, is responsible for efficiently executing ONNX models across CPUs, GPUs, mobile devices, cloud servers, and edge environments.
How is an ONNX model represented internally?An ONNX model is conceptually represented as a directed graph. Edges represent tensors moving between nodes, and nodes represent operators. Each operator performs a computation on its inputs and passes the result to child nodes. ONNX graphs are strongly typed, so tensor element types and shapes must be defined for model inputs, outputs, and intermediate computations.
What are ONNX operators?ONNX operators are the building blocks used to define model computations. They include mathematical operations, tensor transformations, neural network layers, activation functions, reductions, pooling operations, and control-flow constructs. Examples include Add, MatMul, Softmax, Reshape, LayerNormalization, QuantizeLinear, and Loop. If a required operation does not exist, ONNX can be extended with custom operators.
How can a simple linear regression model be represented in ONNX?A linear regression expression such as Y = XA + B can be represented with two ONNX operators: MatMul and Add. In ONNX form, this becomes Y = Add(MatMul(X, A), B). The graph can be built using ONNX helper functions such as make_tensor_value_info, make_node, make_graph, and make_model.
What is ONNX Runtime used for?ONNX Runtime is used to execute ONNX models efficiently. It supports inference across many environments, including local machines, cloud servers, mobile devices, and edge devices. ORT can use hardware acceleration when available and applies optimizations such as kernel fusion, quantization, graph optimization, and layout transformations to improve inference performance while maintaining accuracy.
How do you run inference with an ONNX model using ONNX Runtime?The typical inference workflow is to create an InferenceSession, prepare input data, retrieve the model input and output names, and call session.run(). For example, in Python, you create a session with rt.InferenceSession(model_path), get names using session.get_inputs() and session.get_outputs(), then pass a dictionary mapping input names to NumPy arrays into session.run().
What are ONNX Runtime execution providers?Execution providers are interfaces that allow ONNX Runtime to use specific hardware or software acceleration backends. They assign supported nodes or subgraphs to the best available compute backend. Examples include CPUExecutionProvider, CUDAExecutionProvider, Intel OpenVINO, Intel oneDNN, NVIDIA TensorRT, DirectML, AMD ROCm, Qualcomm QNN, Android Neural Networks API, and others. You can check available providers with onnxruntime.get_available_providers().
How can ONNX improve LLM inference on CPU or GPU?For LLMs, ONNX can improve inference by converting models from frameworks such as PyTorch into a portable graph format and then executing them with ONNX Runtime optimizations. In the chapter’s BERT CPU example, ONNX Runtime inference was faster than PyTorch CPU inference, and further optimization improved performance again. On GPU, ONNX Runtime can use providers such as CUDAExecutionProvider to run the converted model with hardware acceleration.
What is I/O binding in ONNX Runtime and why is it useful?I/O binding is an ONNX Runtime feature that lets inputs and outputs be bound directly to a target device, such as a CUDA GPU. By default, ORT maps data to CPU memory, which can cause unnecessary CPU-GPU data transfers when inference runs on GPU. With IOBinding, input and output tensors can remain on the GPU, reducing data transfer overhead and improving performance, especially for GPU-accelerated LLM inference.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Domain-Specific Small Language Models ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Domain-Specific Small Language Models ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Domain-Specific Small Language Models ebook for free