Skip to content
ImagineWorld

Exploring ONNX

node_idnode-book_build-small-language-model_chapter-05-exploring-onnx
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num5
chapter_titleExploring ONNX
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

This chapter covers

  • The ONNX standard format
  • The ONNX runtime
  • How ONNX can be useful for LLMs, with or without hardware acceleration

This chapter introduces the ONNX framework, which plays an important role in model optimization, quantization, and portability across frameworks and hardware vendors. If you’re new to ONNX, take the time to absorb the concepts in this chapter—they’re used heavily in later chapters.

ONNX (Open Neural Network Exchange, https://onnx.ai/) is an open standard for ML interoperability. First released in 2017, it is now a graduate project of the Linux Foundation for Artificial Intelligence (LFAI, https://lfai.data.foundation/). ONNX aims to improve interoperability across machine learning (ML) and deep learning (DL) frameworks (including Keras, TensorFlow, PyTorch, scikit-learn,

XGBoost, and others) and to maximize performance across hardware accelerators (not just NVIDIA, but also Intel OpenVINO, Habana, Qualcomm, Apache TVM, Hugging Face Optimum, and more). Figure 5.1 gives a high-level view of the ONNX ecosystem, including the framework- and platform-agnostic model format and the optional ONNX Runtime.

graph TD
    FW["ML/DL frameworks<br/>(Keras, TensorFlow, PyTorch, mxnet, scikit-learn, XGBoost)"]
    M["ONNX model"]
    RT["ONNX runtime"]
    HW["Hardware: CPU · GPU · TPU · FPGA"]
    DV["Devices"]
    FW --> M
    M --> RT
    RT --> HW
    HW --> RT
    HW --> DV

[!visual-conversion] Figure 5.1 — ONNX overview (p. 82)

As ML and DL frameworks evolve, portability becomes critical—what we use today may not be what we’ll use tomorrow. ONNX is a robust open standard that reduces lock-in to specific frameworks and hardware accelerators, helping ensure an organization’s models remain usable over time.

ONNX is a community project with open governance, so anyone can contribute. It was created at Facebook and was soon backed by other companies such as Microsoft, IBM, Huawei, Intel, AMD, Arm, and Qualcomm. Since then, it has grown into a widely adopted standard for ML/DL inference. Figure 5.2 lists the companies that currently support ONNX.

ONNX consists of two projects: the ONNX format and the ONNX runtime. This section and section 5.2 cover the ONNX format, while sections 5.3 and 5.4 cover the ONNX runtime.

Organizations supporting the ONNX initiative, as listed in the print (reading left to right, top to bottom):

Baidu · BECKHOFF · BITMAIN · Cadence · CEVA · ClearBlade · Datakalab · Facebook Open Source · FuriosaAI · Graphcore · Groq · Habana · HAILO · Hewlett Packard Enterprise · HUAWEI · IBM · Idein Inc · Intel · MathWorks · MAXAR · MediaTek · Xiaomi (mi) · Microsoft · MosaicML · NVIDIA · NXP · OctoML · ORACLE · OPEN AI LAB · Preferred Networks · RECOGNI · SIEMENS · SONY · Qualcomm · Quantco · SAS · SenseTime · Skymizer · Synopsys · Tencent · Tsing Micro · Unity · Verizon Media · VMware · Wolfram · Yandex · ZAMA · ZETANE

[!visual-conversion] Figure 5.2 — The list of organizations supporting the ONNX initiative (p. 83)

Besides being cross-framework, ONNX provides APIs for multiple programming languages. In this book, we’ll use Python (and a little C/C++). Figure 5.3 summarizes all the possible options with ONNX.

Once you’ve trained a model in a DL framework (or received one from someone else), you can convert it to ONNX (and optimize it) and then choose from the following options:

  • Executing it directly in the ONNX Runtime (or any other runtime supported by the framework)
  • Converting it to another DL framework
  • Optimizing it further through quantization

At the end of the process described in either of the last two options, you can run the final model with any supported runtime. In figure 5.3, the block where the model is run in another framework is highlighted in a different color because it’s out of scope for this book. From here on, we’ll discuss converting models to ONNX format and optimizing and quantizing them, and we’ll reference other Python libraries that support this standard.

ONNX defines a common set of operators and a standard file format for storing trained ML/DL models and pipelines, with enough detail to move them between platforms. ONNX can also compile stored operations to lower-level languages for embedding on a range of devices, including edge devices. Conceptually, an ONNX file defines a directed graph: each edge represents a typed tensor moving from one node to the next. The nodes are called operators: they consume inputs and pass their results to their

graph LR
    SRC["Transformer model in any DL framework (TensorFlow, PyTorch, etc.)"]
    ONNX["Converted Transformer model in ONNX format"]
    QUANT["Quantized Transformer model (ONNX format)"]
    OTHER["Converted Transformer model in another framework"]
    EXEC["Execution of quantized Transformer model in any execution provider (including the ONNX runtime)"]
    SRC -->|Convert| ONNX
    ONNX -->|Optimize| QUANT
    ONNX -->|Convert| OTHER
    ONNX -->|Execute| EXEC
    QUANT -->|Execute| EXEC
    OTHER -->|Execute| EXEC

[!visual-conversion] Figure 5.3 — The possible operations on ML/DL models in ONNX (p. 84) children. ONNX’s standard operations are broad enough to express most ML/AI workloads, and you can extend them with custom operators when needed.

ONNX provides a common language that any ML/DL framework can use to describe its models, making production deployment easier. It also lets you build a unique deployment pipeline independent of the framework used to create the model. This framework includes a Python runtime for evaluating ONNX models and operators, but use it with care: it’s intended to clarify ONNX semantics and help with debugging, not for production—especially when you need high performance.

Regardless of the ML/DL model or framework, building an ONNX graph involves defining a combination of operators, as described in the next section.

Operators are the basic building blocks for defining ONNX models; almost any ML/DL model from various frameworks can be described using them. ONNX operators include standard matrix operations, reductions, image transformations, deep neural network layers, and activation functions. Table 5.1 provides a nonexhaustive list of operators relevant to LLMs (see the official ONNX documentation for the complete list).

Table 5.1 The most relevant ONNX operators for LLMs

OperatorDescription
AddPerforms element-wise binary addition. It supports multidirectional broadcasting (like NumPy).
AndReturns the tensor resulted from performing the and logical operation elementwise on the input tensors

Table 5.1. The most relevant ONNX operators for LLMs (continued)

OperatorDescription
ArgMaxComputes the indices of the max elements of the input tensor’s element along the provided axis
ArgMinComputes the indices of the min elements of the input tensor’s element along the provided axis
AtanCalculates the arctangent (inverse of tangent) of the given input tensor, element-wise
AveragePoolConsumes an input tensor and applies average pooling across the tensor according to kernel sizes, stride sizes, and pad lengths. Average pooling consists of computing the average on all values of a subset of the input tensor according to the kernel size and downsampling the data into the output tensor for further processing.
BatchNormalizationApplies batch normalization to deep neural networks
ConvApplies convolution to the input tensor
DFTComputes the discrete fourier transform of the input
DetCalculates the determinant of a square matrix (or a batch of square matrices)
DivPerforms element-wise binary division of the input
EqualReturns the tensor resulted from performing the equal logical operation element-wise on the input tensors
ExpCalculates the exponential of the given input tensor, element-wise
FloorTakes one input tensor and produces an output tensor where the floor is y = floor(x), applied element-wise
GreaterOrEqualReturns the tensor resulted from performing the greater_equal logical operation element-wise on the input tensors
IdentityThe identity operator
IsNaNReturns which elements of the input are NaN
LayerNormalizationLayer normalization defined as a function
LessOrEqualReturns the tensor resulted from performing the less equal logical operation element-wise on the input tensors
LoopThe generic loop construct
MatMulThe matrix product
MaxPoolConsumes an input tensor and applies max pooling across the tensor according to kernel sizes, stride sizes, and pad lengths. The max pooling operation consists of computing the max on all values of a subset of the input tensor according to the kernel size and downsampling the data into the output tensor for further processing.
MeanElement-wise mean of each of the input tensors

Table 5.1 The most relevant ONNX operators for LLMs (continued)

OperatorDescription
PadGiven a tensor containing the data to be padded, a tensor containing the number of start and end pad values for axis, and, optionally, a mode and a constant value, a padded tensor is generated as output.
QuantizeLinearThe linear quantization operator. It consumes a high-precision tensor, a scale, and a zero point to compute the low-precision/quantized tensor.
ReciprocalTakes one input tensor and produces one output tensor where the reciprocal, y=1/xy = 1/x, is applied to the tensor element-wise
RegexFullMatchPerforms a full regex match on each element of the input tensor. If an element fully matches the regex pattern specified as an attribute, the corresponding element in the output is true, and it is false otherwise.
ReshapeReshapes the input tensor. First input is the data tensor; second input is a shape tensor which specifies the output shape. It outputs the reshaped tensor.
SoftmaxComputes the normalized exponential values for the given input: Softmax(input,axis)=Exp(input)/ReduceSum(Exp(input),axis=axis,keepdims=1)Softmax(input, axis) = Exp(input) / ReduceSum(Exp(input), axis=axis, keepdims=1) The axis attribute indicates the dimension along which Softmax will be performed. The output tensor has the same shape and contains the Softmax values of the corresponding input.
TransposeTransposes the input tensor
UniqueFinds the unique elements of a tensor. When an optional attribute axis is provided, unique subtensors sliced along the axis are returned. Otherwise, the input tensor is flattened, and unique values of the flattened tensor are returned.

ONNX is optimized for numerical computation with tensors (multidimensional arrays) defined by an element type, a shape, and a contiguous array of values. Although ONNX initially supported only 32-bit floating-point values, later versions added all common types. You can programmatically list all the supported ONNX types:

import re
from onnx import TensorProto
reg = re.compile('^[0-9A-Z_]+$')
values = {}
for att in sorted(dir(TensorProto)):
if att in {'DESCRIPTOR'}:
continue
if reg.match(att):
values[getattr(TensorProto, att)] = att
for i, att in sorted(values.items()):
si = str(i)
if len(si) == 1:
si = " " + si
print("%s: onnx.TensorProto.%s" % (si, att))

The preceding code prints a list of supported types to standard output:

0: onnx.TensorProto.UNDEFINED
1: onnx.TensorProto.FLOAT
2: onnx.TensorProto.UINT8
3: onnx.TensorProto.INT8
4: onnx.TensorProto.UINT16
5: onnx.TensorProto.INT16
6: onnx.TensorProto.INT32
7: onnx.TensorProto.INT64
8: onnx.TensorProto.STRING
9: onnx.TensorProto.BOOL
10: onnx.TensorProto.FLOAT16
11: onnx.TensorProto.DOUBLE
12: onnx.TensorProto.UINT32
13: onnx.TensorProto.UINT64
14: onnx.TensorProto.COMPLEX64
15: onnx.TensorProto.COMPLEX128
16: onnx.TensorProto.BFLOAT16
17: onnx.TensorProto.FLOAT8E4M3FN
18: onnx.TensorProto.FLOAT8E4M3FNUZ
19: onnx.TensorProto.FLOAT8E5M2
20: onnx.TensorProto.FLOAT8E5M2FNUZ

As a concrete example of using the ONNX API, let’s consider a linear regression model, represented by the following expression:

Y=XA+BY = XA + B

All the variables are matrices. In ONNX, we must represent this with two operators, MatMul and Add (see the operator list in table 5.1):

y = Add(MatMul(X, A), B)

To build the graph, we’ll use four functions from the ONNX API:

  • make_tensor_value_info—Declares an input or output variable with a given shape and type
  • make_node—Creates a node from an operation and its inputs and outputs
  • make_graph—Creates an ONNX graph from the objects created by the previous two functions
  • make_model—Merges the graph with additional metadata

ONNX is strongly typed, so you must define the shape and type of each function’s inputs and outputs. ONNX is built on protobuf (https://github.com/protocolbuffers/protobuf), a language- and platform-neutral format for serializing structured data. protobuf provides the definitions needed to describe an ML/DL model; ONNX is used to serialize and deserialize it. protobuf is responsible for keeping the saved graph compact.

To implement this in code (using the Python bindings), we first need to import the required classes and functions:

from onnx import TensorProto
from onnx.helper import (
make_model, make_node, make_graph,
make_tensor_value_info)
from onnx.checker import check_model

The imported functions include those listed previously, plus check_model, which checks the consistency of a created ONNX model. TensorProto is the ONNX class that defines a tensor, and it’s one of several protobuf-based structure classes. You can list all these classes programmatically as follows:

import onnx
import pprint
pprint.pprint([p for p in dir(onnx)
if p.endswith('Proto') and p[0] != '_'])

It returns the following output:

['AttributeProto',
'FunctionProto',
'GraphProto',
'MapProto',
'ModelProto',
'NodeProto',
'OperatorProto',
'OperatorSetIdProto',
'OperatorSetProto',
'OptionalProto',
'SequenceProto',
'SparseTensorProto',
'StringStringEntryProto',
'TensorProto',
'TensorShapeProto',
'TrainingInfoProto',
'TypeProto',
'ValueInfoProto']

We can define a linear regression model by first declaring the matrices involved:

X = make_tensor_value_info('X', TensorProto.FLOAT, [None, None])
A = make_tensor_value_info('A', TensorProto.FLOAT, [None, None])
B = make_tensor_value_info('B', TensorProto.FLOAT, [None, None])
Y = make_tensor_value_info('Y', TensorProto.FLOAT, [None])

Next, we’ll create the graph nodes (operations for this model implementation):

node1 = make_node('MatMul', ['X', 'A'], ['XA'])
node2 = make_node('Add', ['XA', 'B'], ['Y'])

Then we can create the graph:

graph = make_graph([node1, node2], 'lr', [X, A, B], [Y])
onnx_model = make_model(graph)

Check the model consistency as follows:

check_model(onnx_model)

Finally, we can serialize it with the SerializeToString method:

with open("linear_regression.onnx", "wb") as f:
f.write(onnx_model.SerializeToString())

We can inspect the ONNX model’s structure in two ways. First, print the model variable to the screen:

print(onnx_model)

That command prints the model structure in ASCII format to standard output, as follows:

ir_version: 9
graph {
node {
input: "X"
input: "A"
output: "XA"
op_type: "MatMul"
}
node {
input: "XA"
input: "B"
output: "Y"
op_type: "Add"
}
name: "lr"
input {
name: "X"
type {
tensor_type {
elem_type: 1
shape {
dim {
}
dim {
}
}
}
}
}
input {
name: "A"
}
type {
tensor_type {
elem_type: 1
shape {
dim {
}
dim {
}
}
}
}
input {
name: "B"
type {
tensor_type {
elem_type: 1
shape {
dim {
}
dim {
}
}
}
}
}
output {
name: "Y"
type {
tensor_type {
elem_type: 1
shape {
dim {
}
}
}
}
}
opset_import {
version: 21
}

Alternatively, we can visualize an ONNX graph with the open source Netron library (https://github.com/lutzroeder/netron), which supports ONNX. The output will look similar to figure 5.4 (you can also include metadata in the rendering).

The saved ONNX graph can be restored at any time using the load function:

from onnx import load
with open("linear_regression.onnx", "rb") as f:
onnx_model = load(f)

The ONNX format defines the ML/DL models converted to this framework. Another key part of the ecosystem is the ONNX Runtime (ORT, https://onnxruntime.ai/), which executes ONNX models efficiently across a wide range of hardware and software platforms (illustrated earlier in figure 5.1). ORT supports the deployment of ONNX models on local or cloud servers, as well as on mobile phones and edge devices, for consistent performance across environments. When available, ORT uses hardware acceleration for faster inference. It also includes optimizations such as kernel fusion, quantization, and layout transformations to speed execution while maintaining good accuracy. Although ORT supports both training and inference, it’s most often used for inference, with training left to the original ML/DL framework. Training with ORT is out of scope for this book.

NOTE ORT provides bindings for multiple programming languages ; in this book, we’ll use Python.

The inference process follows a fixed set of steps. Once we’ve trained a model and converted it to ONNX, or implemented one directly with the ONNX API (such as the linear regression model in section 5.2), we load it and create an inference session (using ORT’s InferenceSession class):

import onnxruntime as rt
onnx_model_path = "path_to_the_onnx_model"
session = rt.InferenceSession(onnx_model_path)

Next, we prepare the model input (in this example, it will be a NumPy array):

import numpy as np
input_data = np.array([[2.0, 4.0, 6.0, 8.0]], dtype=np.float32)

We can now run inference:

input_name = session.get_inputs()[0].name
output_name = session.get_outputs()[0].name
result = session.run([output_name], {input_name: input_data})

Finally, we can print the result:

print(f"Output: {result[0]}")
graph TD
    X(["X"]) -->|"?×10"| MM["MatMul<br/>B ⟨10×1⟩"]
    MM --> AD["Add<br/>B ⟨1⟩"]
    AD --> RS["Reshape<br/>shape ⟨2⟩"]
    RS -->|"?×1"| V(["variable"])

[!visual-conversion] Figure 5.4 — Visualizing a linear regression model in ONNX with Netron (p. 91)

When passing input values to the model, make sure you use the correct input name. You can retrieve it from the inference session object with get_inputs, which returns the list of names for a model’s inputs. Similarly, get_outputs returns the model’s output names. The command sequence for ORT inference is always the same; what varies by architecture is input preprocessing, output postprocessing, and how you handle multiple inputs and outputs.

A JavaScript library for running ONNX models in web browsers or on Node.js is also available. It’s called ONNX Runtime Web (https://microsoft.github.io/onnxruntime-web-demo), and it’s built on WebAssembly and WebGL. It supports CPU and GPU execution and enables interactive, install-free, device-independent ML, with lower server-client latency and improved privacy and security. After you specialize your model, convert it to ONNX, and optimize it, you can use this as another serving option.

To get the most from the underlying hardware on which an ONNX model runs, ORT uses runtime (execution) providers. These interfaces let you deploy ONNX models across environments and optimize execution by using each platform’s compute capabilities. Through a dedicated execution provider, ORT assigns specific nodes or subgraphs to run on the available hardware, drivers, and related libraries in the deployment environment. Figure 5.5, from the official ORT documentation, shows how ORT improves a model’s execution for a given hardware specification.

graph TD
    M["ONNX model"] --> IMG["In-memory graph"]
    IMG --> GP["Graph partitioner"]
    GP --> PR["Provider registry"]
    IN["Input data"] --> RUN["Parallel, distributed graph runner"]
    GP --> RUN
    RUN --> EP["Execution providers"]
    EP --> CPU["CPU"]
    EP --> GPUEP["GPU-EP"]
    EP --> E1["..."]
    EP --> E2["..."]
    GPUEP -.-> LIB["GPU Libraries"]
    GPUEP -.-> DRV["Drivers"]
    PR --> RUN
    RUN --> OUT["Output result"]

[!visual-conversion] Figure 5.5 — The ONNX Runtime execution model (p. 92)

At the time of writing, ORT offers many execution providers. Some are production-ready; others are preview releases for evaluation. Providers marked as in review are generally stable and may be suitable for production, but test carefully before deploying an ONNX model with any provider still labeled as in preview.

Here are ORT’s currently stable execution providers:

  • Default CPU—Vendor-agnostic CPU.
  • Intel OpenVINO—Uses the OpenVINO toolkit (https://mng.bz/Jw5p) on CPUs and GPUs, including edge and mobile devices.
  • Intel oneDNN—Uses optimized primitives from the Intel Math Kernel Library for Deep Neural Networks (Intel DNNL). CPU-only.
  • XNNPACK—Uses XNNPACK (https://github.com/google/XNNPACK), an optimized floating-point NN inference library for ARM (Android/iOS), Web Assembly, and x86.
  • NVIDIA CUDA—Enables hardware-accelerated computation on CUDA-enabled NVIDIA GPUs.
  • NVIDIA TensorRT—Uses NVIDIA’s TensorRT engine (https://developer.nvidia.com/tensorrt) on supported NVIDIA GPUs.
  • DirectML—Uses DirectML’s low-level API for ML (https://mng.bz/wZw7); Windows GPUs only.
  • AMD MIGraphX—AMD’s MiGraphX optimization engine for AMD GPUs (https://github.com/ROCm/AMDMIGraphX).
  • AMD ROCm—For AMD GPUs with ROCm (https://mng.bz/qRwK).
  • Android Neural Networks API—A unified interface to CPUs, GPUs, and neural network accelerators on Android devices (https://mng.bz/7QOx).
  • Qualcomm QNN—Uses the Qualcomm AI Engine Direct SDK (https://mng.bz/mZwn) on Qualcomm chipsets.

This is the current list of ORT execution providers still in preview:

  • Huawei CANN—Uses the CANN Execution Provider with Huawei Ascend hardware.
  • AZURE—Invokes a remote Azure endpoint for inference.

You can programmatically check the available providers in the destination environment:

import onnxruntime as rt
rt.get_available_providers()

This returns a Python list. For example, on a system with a CPU and an NVIDIA GPU (with CUDA drivers installed), the preceding method returns the following:

[‘CPUExecutionProvider’, ‘CUDAExecutionProvider’]

If multiple providers are available, you can tell ORT the order in which to try them. Here’s an example:

providers_list = ['CUDAExecutionProvider', 'CPUExecutionProvider']
sess = rt.InferenceSession("model.onnx", providers=providers_list)

Here, we tell ORT to prefer the CUDA provider (when available) over others in the execution environment.

Now that we’ve covered the main ONNX format and runtime concepts, it’s time to see how we can use them with LLMs. This section focuses on CPU-only setups; the next section covers the same ideas for when GPUs are available. The code in this section is included in a companion Colab notebook.

Our first LLM example uses a BERT-based model called bert-base-uncased (https://huggingface.co/google-bert/bert-base-uncased). It uses Hugging Face’s Transformers and Datasets libraries. The execution environment must have the onnx and CPU-only onnxruntime Python packages installed:

Terminal window
pip install onnx onnxruntime

Next, we need to download the model from the Hugging Face Hub:

from transformers import AutoModelForQuestionAnswering, BertTokenizer
model_id = 'google-bert/bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(model_id)
model = AutoModelForQuestionAnswering.from_pretrained(model_id)
model.eval()

To test the model, we’ll use a subset of the SQUAD dataset (Stanford Question Answering Dataset, https://huggingface.co/datasets/squad), available from the Hugging Face Hub via the Datasets library:

from datasets import load_dataset
samples_count = 200
squad = load_dataset("squad", split="validation[:+" + str(samples_count) + "]")

Only 200 samples will be used. The following example shows their structure:

{'id': '56be4b0acb8001400a502ec',
'title': 'Super_Bowl_50',
'context': 'Super Bowl 50 was an American football game to determine the
champion of the National Football League (NFL) for the 2015 season. The
American Football Conference (AFC) champion Denver Broncos defeated the
National Football Conference (NFC) champion Carolina Panthers 24-10 to earn
their third Super Bowl title. The game was played on February 7, 2016, at
Levi\'s Stadium in the San Francisco Bay Area at Santa Clara, California.
As this was the 50th Super Bowl, the league emphasized the "golden
anniversary" with various gold-themed initiatives, as well as temporarily
suspending the tradition of naming each Super Bowl game with Roman numerals
(under which the game would have been known as "Super Bowl L"), so that the
logo could prominently feature the Arabic numerals 50.',
'question': 'Which NFL team represented the AFC at Super Bowl 50?',
'answers': {'text': ['Denver Broncos', 'Denver Broncos', 'Denver Broncos'],
'answer_start': [177, 177, 177]}

In this example, we’ll use the context and question fields to benchmark different model versions on answer generation.

Let’s create a directory to store the ONNX-converted model:

import os
output_dir = os.path.join(".", "onnx_models")
onnx_model_filename = 'bert-base-uncased.onnx'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
export_model_path = os.path.join(output_dir, onnx_model_filename)

We’ll use a test sample to run the model once at the start of the conversion process (here we’ll use the first item in the list, though any of the 200 retrieved samples will work):

tokenized_inputs = tokenizer(squad["question"][0],
squad["context"][0], return_tensors="pt")
inputs = {
'input_ids': tokenized_inputs['input_ids'],
'input_mask': tokenized_inputs['attention_mask'],
'segment_ids': tokenized_inputs['token_type_ids']
}

Then we’ll start the conversion:

import torch
with torch.no_grad():
symbolic_names = {0: 'batch_size', 1: 'max_seq_len'}
torch.onnx.export(model,
args=tuple(inputs.values()),
f=export_model_path,
opset_version=15,
do_constant_folding=True,
input_names=['input_ids',
'input_mask',
'segment_ids'],
output_names=['start', 'end'],
dynamic_axes={'input_ids': symbolic_names,
'input_mask': symbolic_names,
'segment_ids': symbolic_names,
'start': symbolic_names,
'end': symbolic_names})

We’ll use PyTorch’s ONNX export function, passing the model to convert, the destination directory, the ONNX version (1.15.0 at the time of writing), and the model’s input and output names. We’ll also enable constant folding for optimization and set variable-length axes so the model can run with different batch sizes and variable numbers of input and output tokens. Figure 5.6 shows part of the ONNX graph for the converted model (cropped for readability).

You can validate the exported model with the check_model function introduced in section 5.1:

from onnx.checker import check_model
check_model(export_model_path, full_check=True)

If you get no error message, the model’s schema is valid. To validate the full architecture, run inference on a few samples (or the full test set) with both the original model and the ONNX-converted one, and compare their outputs. NumPy provides the allclose function for this:

import numpy as np
for i in range(10):
np.allclose(ort_outputs[i], outputs[i].cpu(), rtol=1e-05, atol=1e-04)

In the preceding code snippet, we assume that we’ve run inference with both the original and converted models on the test set and saved the output in two arrays: outputs and ort_outputs. The allclose function returns True when the arrays are element-wise equal within a tolerance defined by rtol (relative tolerance) and atol (absolute

dslm-fig-5.6-part-of-the-onnx-graph.png

[!visual-conversion] Figure 5.6 — Part of the ONNX graph for the converted bert-base-uncased model (one attention block) (p. 97)

tolerance), which are typically very small values. allclose evaluates the following formula:

absolute(ort_outputs[i] - outputs[i]) <= (atol + rtol *
absolute(outputs[i]))

After exporting and verifying the model, we can run inference. First, we’ll create an ONNX Runtime session:

import onnxruntime
import numpy
sess_options = onnxruntime.SessionOptions()
session = onnxruntime.InferenceSession(export_model_path,
sess_options, providers=['CPUExecutionProvider'])

Then we can run inference in the session as follows:

inputs = tokenizer(squad["question"][0],
squad["context"][0], return_tensors="np")
ort_inputs = {
'input_ids': full_inputs['input_ids'],
'input_mask': full_inputs['attention_mask'],
'segment_ids': full_inputs['token_type_ids']
}
ort_outputs = session.run(None, ort_inputs)

The inputs are tokenized into NumPy arrays (not PyTorch tensors, as in the original model). We then explicitly set the expected inputs for the architecture (for example, input_ids, input_mask, and segment_ids for this BERT model).

If you run the notebook’s benchmark on the full test set for both models (original and ONNX-converted), you’ll see results like these:

PyTorch CPU Average inference time = 455.49 ms
OnnxRuntime cpu Average inference time = 373.10 ms

ONNX’s average inference time is about 18% lower.

Finally, the notebook code uses the ONNX API to further optimize the converted model, using the ONNX optimizer class’s optimize_model function:

from onnxruntime.transformers import optimizer
optimized_model_path = os.path.join(output_dir,
'bert-base-uncased.onnx_opt_cpu.onnx')
optimized_model = optimizer.optimize_model(export_model_path,
model_type='bert', num_heads=12, hidden_size=768)
optimized_model.save_model_to_file(optimized_model_path)

Running the benchmark on this optimized model produces the following:

OnnxRuntime cpu Average inference time = 355.48 ms

Let’s now look at running ONNX models on a GPU. As a first example, let’s consider bert-base-uncased, the same model as in section 5.5, but in an environment with an NVIDIA GPU and CUDA drivers installed. The full code for this example is available in a companion Colab notebook. Again, we use the Hugging Face Transformers and Datasets libraries. In addition to the onnx library, you’ll need onnxruntime for GPU:

Terminal window
pip install onnx onnxruntime-gpu

The code to download the model from the HF Hub is nearly identical to the section 4.5 example:

import torch
from transformers import AutoModelForQuestionAnswering, BertTokenizer
device = torch.device("cuda")
model_id = 'bert-base-uncased'
tokenizer = BertTokenizer.from_pretrained(model_id)
model = AutoModelForQuestionAnswering.from_pretrained(model_id)
model.eval()
model.to(device)

The only difference here is that we load the model into GPU memory because we’re also using hardware acceleration to convert the model to ONNX.

As in section 5.5, we use SQUAD as the reference dataset for testing and validation. See the previous section for the code to download a subset of samples.

The conversion code is the same as for CPUs, so we won’t duplicate it here; see section 5.5 or this section’s companion notebook. Inference with the ONNX-converted model is also similar, but you must configure the ONNX inference session to use the CUDA execution provider as follows:

session = onnxruntime.InferenceSession(export_model_path, sess_options,
providers=['CUDAExecutionProvider'])

That’s all you need to run an ONNX-converted model on a GPU runtime in a standard way. There are other considerations, but before we explore them, let’s look at another example.

The previous example and the one in section 5.5 use encoder-only models. Now we’ll look at a decoder-only model: GPT-2 small (https://huggingface.co/openai-community/gpt2). The code in this section is included in the companion Colab notebook.

Let’s download the model from the Hugging Face Hub:

import torch
from transformers import GPT2Tokenizer, AutoModelForCausalLM
model_id = 'openai-community/gpt2'
tokenizer = GPT2Tokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
device = torch.device("cuda")
model.eval().to(device)

Although this isn’t required, we moved the model checkpoints to GPU memory and will use the GPU to convert the model to ONNX. (You can also run the conversion on CPU.) Now let’s create a directory to store the converted model:

import os
output_dir = os.path.join(".", "onnx_models")
onnx_model_filename = 'bert-base-uncased.onnx'
if not os.path.exists(output_dir):
os.makedirs(output_dir)
export_model_path = os.path.join(output_dir, onnx_model_filename)

Next, we’ll prepare a sample input. For this use case, we’ll set the tokenizer’s return_attention_mask argument to False, since the attention mask isn’t used:

tokenized_inputs = tokenizer("The story so far: in the beginning, the universe was created.",
return_attention_mask=False,
return_tensors="pt")
tokenized_inputs.to(device)
inputs_sample = {
'input_ids': tokenized_inputs['input_ids']
}

Finally, we’ll start the conversion process:

with torch.no_grad():
torch.onnx.export(model,
inputs_sample,
export_model_path,
export_params=True,
opset_version=15,
input_names=['input_ids']
)

We can run inference with the exported model as in the previous BERT example—create an inference session, choose the CUDA runtime provider, and call the run method:

import onnxruntime
import numpy
session = onnxruntime.InferenceSession(export_model_path,
providers=["CUDAExecutionProvider"])
onnx_input_ids = tokenizer("The story so far: in the beginning, the universe was created.",
return_attention_mask=False,
return_tensors="np")
ort_inputs = {
"input_ids": onnx_input_ids['input_ids']
}
ort_outputs = session.run(None, ort_inputs)

In the examples so far, we’ve assumed that converting a model to ONNX automatically applies the best possible optimizations. This is often true, but sometimes extra steps are needed. You can usually do this programmatically; manually inspecting the generated ONNX graph should be a last resort. One way to do this (not the only one—we’ll cover more later) is to use the ONNX Runtime library’s built-in Transformer optimizer. Continuing the GPT-2 example, here’s how we can apply it to an already converted model:

from onnxruntime.transformers import optimizer
optimized_model_path = os.path.join(output_dir, 'gpt-2-onnx_opt_gpu.onnx')
optimized_model = optimizer.optimize_model(export_model_path,
model_type='gpt2',
use_gpu=True,
num_heads=12,
hidden_size=768)
optimized_model.save_model_to_file(optimized_model_path)

We use the optimizer’s optimize_model method, as in the earlier bert-base-uncased example. We pass the full path to the converted model, the LLM family type, and the number of heads and hidden size, and we specify GPU optimization. You can also set the graph optimization level: 0 (none; the default), 1 (basic), 2 (extended), or 99 (all, including layout). The same code applies to LLMs with architectures other than GPT-2. Basic optimization performs constant folding (statically computing parts of the graph that rely only on constant initializers), removes redundant nodes (such as identity, slice, unsqueeze, and dropout), and applies semantics-preserving fusions. Extended optimization applies more complex fusions after graph partitioning, and only to nodes assigned to the CPU, CUDA, or ROCm (AMD Radeon Open Compute Ecosystem) execution provider. Layout optimization changes the data layout for applicable nodes for higher performance; it runs after graph partitioning and only for nodes assigned to the CPU execution provider.

ONNX optimizations can be done offline or online. The previous code snippet is an example of offline optimization. Alternatively, you can enable the same optimizations at inference time by setting the ONNX Runtime session mode, as follows:

import onnxruntime as rt
sess_options = rt.SessionOptions()
sess_options.graph_optimization_level = rt.GraphOptimizationLevel.ORT_ENABLE_EXTENDED
sess_options.optimized_model_filepath = "<model_path\optimized_model.onnx>"
session = rt.InferenceSession(None, sess_options)

The optimization levels are defined by the GraphOptimizationLevel class:

GraphOptimizationLevel.ORT_DISABLE_
GraphOptimizationLevel.ORT_ENABLE_BASIC
GraphOptimizationLevel.ORT_ENABLE_EXTENDED
GraphOptimizationLevel.ORT_ENABLE_ALL

In online mode, ONNX Runtime applies all enabled graph optimizations when the session is initialized, before inference runs. This can increase model startup time (especially for complex models), which can make it unsuitable for production. In offline mode, ONNX Runtime applies the optimizations and then serializes the optimized model to disk. Subsequent startups are faster because the model is already optimized.

Before we move on, consider input and output data when running ONNX models with execution providers (CPU and GPU). So far, you’ve learned that ONNX models consist of a computation graph implemented as optimized operator kernels for different hardware, and that ONNX Runtime (ORT) orchestrates execution through execution providers for a specific target (CPU, GPU, and so on). But what about the data consumed and produced?

By default, ORT places data—regardless of structure (NumPy arrays, dictionaries, or lists of NumPy arrays)—on the CPU. That’s fine when there’s no hardware acceleration, but it’s not ideal when a GPU is available and the inference session is configured to run on the GPU first. In that case, data is copied between CPU and GPU, adding unnecessary overhead. ORT provides a custom data structure that supports ONNX data formats and lets you place data on a device, such as a CUDA-capable GPU. It’s called IOBinding. With it, input and output data (or just one of them, depending on your configuration) can be placed on the same device where the ONNX graph runs.

You can configure IOBinding programmatically, as you’ll see next. To keep the concept simple, we’ll use a small PyTorch model that sums two tensors, but the same approach applies to more complex models, including LLMs. Let’s define the model:

import torch
def model():
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
def forward(self, x, y):
return x.add(y)
return Model()

Now let’s convert it to ONNX programmatically:

MODEL_FILE = '.model.onnx'
type = torch.float32
sample_x = torch.ones(3, dtype=type)
sample_y = torch.zeros(3, dtype=type)
torch.onnx.export(model(), (sample_x, sample_y),
MODEL_FILE, input_names=["x", "y"], output_names=["z"],
dynamic_axes={"x": {0: "array_length_x"}, "y":
{0: "array_length_y"}})

We’ll create an inference session as usual (assuming the target environment has a GPU and CUDA):

import onnxruntime as rt
providers = ['CUDAExecutionProvider', 'CPUExecutionProvider']
session = rt.InferenceSession(MODEL_FILE, providers=providers)

The new part starts after we’ve created the session. Instead of running inference with run, we’ll use run_with_iobinding. First, we’ll prepare the data for IOBinding. Create an IOBinding instance from the inference session:

binding = session.io_binding()

Create two tensors containing random values, and move them to the GPU:

DEVICE = 'cuda'
x = torch.rand(5).to(DEVICE)
y = torch.rand(5).to(DEVICE)
x_tensor = x.contiguous()
y_tensor = y.contiguous()

Then tell ONNX Runtime to load the model inputs onto the CUDA device:

DEVICE_INDEX = 0
np_type = np.float32
binding.bind_input(
name='x',
device_type=DEVICE,
device_id=DEVICE_INDEX,
element_type=np_type,
shape=tuple(x_tensor.shape),
buffer_ptr=x_tensor.data_ptr(),
)
binding.bind_input(
name='y',
device_type=DEVICE,
device_id=DEVICE_INDEX,
element_type=np_type,
shape=tuple(y_tensor.shape),
buffer_ptr=y_tensor.data_ptr(),
)

You can run inference with IOBinding as follows:

session.run_with_iobinding(binding)

In this example, only the input data is loaded into the device; the output is still moved to the CPU. To use IOBinding for the output as well, allocate a PyTorch tensor for the model output before running inference:

z_tensor = torch.empty(x_tensor.shape, dtype=torch_type,
device=DEVICE).contiguous()

Then bind it, just as you did for the input tensors:

binding.bind_output(
name='z',
device_type=DEVICE,
device_id=DEVICE_INDEX,
element_type=np_type,
shape=tuple(z_tensor.shape),
buffer_ptr=z_tensor.data_ptr(),
)

Other examples with more complex data will be presented in chapters 7 and 8.

  • ONNX is an open standard format for interoperable machine learning models across frameworks and hardware platforms.
  • ONNX Runtime (ORT) efficiently runs ONNX models on CPUs, GPUs, and edge devices.
  • ONNX operators are the building blocks that can describe machine learning models from most frameworks.
  • ONNX supports multiple data types, including float32, int8, int16, int32, int64, and specialized formats like bfloat16.
  • ONNX Runtime execution providers optimize performance by using hardware accelerators such as NVIDIA CUDA.
  • You can optimize ONNX models offline during conversion or online when initializing an inference session.
  • ONNX graph optimizations range from constant folding to node fusion and layout transformations.
  • IOBinding in ONNX Runtime eliminates CPU–GPU copies by keeping data on the target execution device.
  • ONNX-converted models typically achieve faster inference times than their original framework implementations.
  • Validation of ONNX models means verifying schema consistency and ensuring that outputs match those of the original model.
  • ONNX Runtime supports multiple language bindings, but Python offers the most comprehensive API.
  • You can optimize ONNX transformer models with the onnxruntime.transformers.optimizer models.
  • Converting language models to ONNX preserves functionality and enables deployment across diverse production environments.