Skip to content
ImagineWorld

Profiling insights

node_idnode-book_build-small-language-model_chapter-10-profiling-insights
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num10
chapter_titleProfiling insights
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

10 Profiling insights

This chapter covers

  • Profiling ONNX ported models
  • Transforming raw ONNX profiling data into insights
  • Optimizing ONNX graphs for LLMs

Chapter 5 introduced the ONNX format and ONNX Runtime capabilities, first in general and then for LLMs. Chapter 6 covered several approaches, including 8-bit quantization through the ONNX API. This chapter will explore other ONNX features, such as profiling the performance of LLMs ported to ONNX format and tools you can use to extract useful insights from the profiling data.

The ONNX Runtime (ORT) delivers high performance for running machine learning (ML) and deep learning (DL) models across a wide range of hardware. Still, to meet specific key performance indicators (KPIs) for latency, throughput, and memory use, you may need additional model optimizations and runtime configuration for a given use case, model, and device.

The ORT supports in-code performance profiling. It’s disabled by default, but you can enable it during debugging by setting the enable_profiling option to True in an ORT inference session:

import onnxruntime as rt
sess_options = rt.SessionOptions()
sess_options.enable_profiling = True

At runtime, ORT generates a JSON file with performance data such as threading and per-operator latency.

Let’s take a look at what’s in this profiling file, starting with a simple model and then moving on to LLMs. We’ll reuse the linear regression example from section 5.2:

from onnx import TensorProto
from onnx.helper import (
make_model, make_node, make_graph,
make_tensor_value_info)
from onnx.checker import check_model
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])
node1 = make_node('MatMul', ['X', 'A'], ['XA'])
node2 = make_node('Add', ['XA', 'B'], ['Y'])
graph = make_graph([node1, node2], 'lr', [X, A, B], [Y])
onnx_model = make_model(graph)
check_model(onnx_model)

To run inference with this model, we need to create an inference session and specify the execution provider (CPU; no hardware acceleration needed):

from onnxruntime import InferenceSession
sess = InferenceSession(onnx_model.SerializeToString(),
providers=["CPUExecutionProvider"])

We’ll test it with three input arrays of random values:

import numpy as np
res = sess.run(None, {
'X': np.random.randn(2, 2).astype(np.float32),
'A': np.random.randn(2, 2).astype(np.float32),
'B': np.random.randn(2, 2).astype(np.float32)
})

To measure this model’s performance (and spot areas for improvement), we’ll run inference with profiling enabled. There are no other code changes:

import onnxruntime as rt
from onnxruntime import InferenceSession
sess_options = rt.SessionOptions()
sess_options.enable_profiling = True
sess = InferenceSession(onnx_model.SerializeToString(),
sess_options,
providers=["CPUExecutionProvider"])

To access the generated profiling data, we need to use the end_profiling method:

prof = sess.end_profiling()

This method returns the name of the generated JSON file, which follows the onnxruntime_profile_YYYY-MM-DD_hh-mm-ss.json naming convention. The file contents look like this:

[
{"cat": "Session","pid": 21460,"tid": 14412,"dur": 36164,"ts": 7,
"ph": "X","name": "model_loading_array","args": {}},
{"cat": "Session","pid": 21460,"tid": 14412,"dur": 1430,"ts": 36425,
"ph": "X","name": "session_initialization","args": {}},
{"cat": "Node","pid": 21460,"tid": 14412,"dur": 2,"ts": 34744604,
"ph": "X","name": "MatMul_0_fence_before","args": {"op_name": "MatMul"}},
{"cat": "Node","pid": 21460,"tid": 14412,"dur": 164,"ts": 34744616,
"ph": "X","name": "MatMul_0_kernel_time","args": {"parameter_size": "0","provider": "CPUExecutionProvider","op_name": "MatMul","input_type_shape": [{"float": [2,2]},{"float": [2,2]}],"node_index": "0","output_type_shape": [{"float": [2,2]},{"float": [2,2]}],"activation_size": "32","output_size": "16","thread_scheduling_stats": {"main_thread": "session-2-intra-op","thread_id": "14412","block_size": [],"core": -1,"Distribution": 0,"DistributionEnqueue": 0,"Run": 0,"Wait": 0,"WaitRevoke": 0,"sub_threads": {"20796": {"num_run": 0,"core": -1}}}},
{"cat": "Node","pid": 21460,"tid": 14412,"dur": 0,"ts": 34744793,"ph": "X","name": "MatMul_0_fence_after","args": {"op_name": "MatMul"}},
{"cat": "Node","pid": 21460,"tid": 14412,"dur": 0,"ts": 34744806,"ph": "X","name": "Add_1_fence_before","args": {"op_name": "Add"}},
{"cat": "Node","pid": 21460,"tid": 14412,"dur": 56,"ts": 34744808,"ph": "X","name": "Add_1_kernel_time","args": {"parameter_size": "0","provider": "CPUExecutionProvider","op_name": "Add","input_type_shape": [{"float": [2,2]},{"float": [2,2]}],"node_index": "1","output_type_shape": [{"float": [2,2]},{"float": [2,2]}],"activation_size": "32","output_size": "16","thread_scheduling_stats": {"main_thread": "session-2-intra-op","thread_id": "14412","block_size": [],"core": -1,"Distribution": 0,"DistributionEnqueue": 0,"Run": 0,"Wait": 0,"WaitRevoke": 0,"sub_threads": {"20796": {"num_run": 0,"core": -1}}}},
{"cat": "Node","pid": 21460,"tid": 14412,"dur": 0,"ts": 34744879,"ph": "X","name": "Add_1_fence_after","args": {"op_name": "Add"}},
{"cat" : "Session","pid" :21460,"tid" :14412,"dur" :781,"ts" :34744111,"ph"
: "X","name" : "SequentialExecutor::Execute","args" : {}},
{"cat" : "Session","pid" :21460,"tid" :14412,"dur" :828,"ts" :34744075,"ph"
: "X","name" : "model_run","args" : {}}

The JSON profiling file contains raw data for an ONNX inference session, broken down by operator and execution provider. On its own, this data provides little insight, so you need to aggregate and transform it to understand the model’s performance. ONNX Runtime includes Ort_perf_view, which reads this profiling JSON file, renders summarized statistics as treemaps, and computes latency per ONNX operator (for both CPU and GPU). For small models, such as the linear regressor in this example, the view is clean (as shown in figure 10.1) because we use only two ONNX operators.

CPU perf overview

Operation typeCall count
MatMul166
Add56

[!visual-conversion] Figure 10.1 — Ort_perf_view rendering of performance stats for inference on a linear regression ONNX model (p. 197)

The Ort_perf_view visualizations show one square per operator, labeled with the operator name and call count for the profiled run. The box size reflects the proportion of operator calls. For larger models, this view is less useful for performance analysis, though it still provides a 10,000-foot overview of aggregated operator calls (see figure 10.2).

In figure 10.2, you can see that there are thousands of calls for each operator in the ONNX graph for the model under test. Clicking an operator’s box expands that section to show details for each call (input and output values and duration in microseconds), as shown in figure 10.3.

This visualization isn’t very helpful; it just shows raw data without insights. Let’s switch to something better.

dslm-fig-10.2-cpu-perf-overview-showing-performance.png

[!visual-conversion] Figure 10.2 — Ort_perf_view output showing performance stats for inference run on a large ONNX model (p. 198) dslm-fig-10.3-cpu-perf-overview-expanded-view.png

[!visual-conversion] Figure 10.3 — Ort_perf_view expanded view of all Sqrt operator calls during inference for the model under test (p. 198)

10.2 Transforming raw ONNX profiling data into insights

Section titled “10.2 Transforming raw ONNX profiling data into insights”

In this section, we’ll look at a custom implementation that extracts insights from raw ONNX profiling data and presents them in a user-friendly way. To keep this example simple and easy to follow, we’ll use a linear regression model trained in scikit-learn and then converted to ONNX format. The same profiling process, data transformation, and visualization code apply to any ONNX-converted model, including LLMs.

We’ll use scikit-learn’s diabetes dataset for the training and test sets. It contains 442 samples with 10 features each (age, sex, body mass index, average blood pressure, and six blood serum measurements). The target variable is a quantitative measure of disease progression one year after the baseline.

Let’s download the dataset:

from sklearn.datasets import load_diabetes
data = load_diabetes()

Next, split the data into training and test sets:

from sklearn.model_selection import train_test_split
X, y = data.data, data.target
X_train, X_test, y_train, __ = train_test_split(X, y, random_state=11)

We can now train the model using the scikit-learn API:

from sklearn.linear_model import LinearRegression
clr = LinearRegression()
clr.fit(X_train, y_train)

We can convert the trained model to ONNX format using the sklearn-onnx package (https://github.com/onnx/sklearn-onnx):

from skl2onnx import to_onnx
model_def = to_onnx(clr, X_train)

The converted model graph will look like this:

ir_version: 8
producer_name: "skl2onnx"
producer_version: "1.14.0"
domain: "ai.onnx"
model_version: 0
doc_string: ""
graph {
node {
input: "X"
input: "coef"
output: "multiplied"
name: "MatMul"
op_type: "MatMul"
domain: ""
}
node {
input: "multiplied"
input: "intercept"
output: "resh"
name: "Add"
op_type: "Add"
domain: ""
}
node {
input: "resh"
input: "shape_tensor"
output: "variable"
name: "Reshape"
op_type: "Reshape"
domain: ""
}
name: "ONNX(LinearRegression)"
initializer {
dims: 10
dims: 1
data_type: 11
name: "coef"
double_data: -60.219814056772776
double_data: -266.4570523220356
double_data: 523.063411259699
double_data: 310.5134699670048
double_data: -336.1614738106952
double_data: 137.33929238424574
double_data: -131.13923283453687
double_data: -1.1492348017316942
double_data: 622.3286855688127
double_data: 60.46645769168251
}
initializer {
dims: 1
data_type: 11
name: "intercept"
double_data: 152.22822762230342
}
initializer {
dims: 2
data_type: 7
int64_data: -1
int64_data: 1
name: "shape_tensor"
}
input {
name: "X"
type {
tensor_type {
elem_type: 11
shape {
dim {
}
dim {
dim_value: 10
}
}
}
}
{
"output": {
"name": "variable",
"type": {
"tensor_type": {
"elem_type": 11,
"shape": {
"dim": [],
"dim": {
"dim_value": 1
}
}
}
}
},
"opset_import": {
"domain": "",
"version": 13
}
}

We can profile this converted model by creating an inference session with profiling enabled, as explained in section 9.1:

from onnxruntime import InferenceSession, SessionOptions
so = SessionOptions()
so.enable_profiling = True
sess = InferenceSession(model_def.SerializeToString(), so)

We’ll run inference over the test set (111 samples) and stop profiling at the end:

sess.run(None, {'X': X_test})
prof = sess.end_profiling()

The raw profiling data can now be loaded from the JSON file:

import json
with open(prof, "r") as f:
js = json.load(f)

Next, we’ll create a pandas DataFrame from them:

from mlproduct.onnxrt.ops_whole.session import OnnxWholeSession
df = pd.DataFrame(OnnxWholeSession.process_profiling(js))

We used the OnnxWholeSession class from the mlproduct Python library (https://github.com/sdpython/mlproduct/) to convert the JSON content into a cleaner tabular format (see figure 10.4).

catpidtiddurtsphnameargs_op_name
0Session1565213080100822Xmodel_loading_arrayNaN
1Session156521308074271080Xsession_initializationNaN
2Node156521308007636737XMatMul_fence_beforeMatMul
3Node15652130801347636753XMatMul_kernel_timeMatMul
4Node156521308007636903XMatMul_fence_afterMatMul
args_parameter_sizeargs_providerargs_input_type_shapeargs_node
0NaNNaNNaN
1NaNNaNNaN
2NaNNaNNaN
380CPUExecutionProvider[{'double': [111, 10]}, {'double': [10, 1]}]
4NaNNaNNaN

Figure 10.4 The head rows of the profiling data for the regression model example in tabular format

Starting with this cleaner data representation, it’s easier to build visualizations and extract insights. We’ll use the Plotly Express Python charting library (https://plotly .com/python/plotly-express/). For performance analysis, we want to compare the total duration for each ONNX operator in the model graph. To do that, we’ll first group operators by type and calculate the total duration for each one:

gr_dur = df[['dur', "args_op_name"]].groupby("args_op_name").sum().sort_values('dur')

This data can then be displayed in a horizontal bar chart, where the x-axis is total duration (in milliseconds), and the y-axis is the ONNX operator type (see figure 10.5):

fig = px.bar(gr_dur, x='dur',
labels={
"dur": "Duration (ms)",
"args_op_name": "Operation type",
},
title='Duration'
)
fig.show()

dslm-fig-10.5-horizontal-bar-chart-showing-total.png

[!visual-conversion] Figure 10.5 — Total duration (ms) of the three ONNX operators in our linear regression model’s graph (p. 203)

This visualization quickly shows which operators take the most time during a model’s inference. Another useful metric is how often each operator is called. To visualize that, first aggregate by operator type, and then count occurrences for each type, ordering by duration so the chart matches the total-duration view:

gr_n = df[['dur', "args_op_name"]].groupby("args_op_name").count().sort_values('dur')
gr_n = gr_n.loc[gr_dur.index, :]

This information can then be shown in a horizontal bar chart, where the x-axis is the count of occurrences for a given operator, and the y-axis is the ONNX operator type (see figure 10.6):

fig = px.bar(gr_n, x='dur',
labels={
"dur": "Op count",
"args_op_name": "Operation type",
},
title='Occurrences')
fig.show()

For a more complete performance analysis, it’s useful to show not only how often each operator runs but also what share of total inference time it accounts for. To do that, we’ll first calculate each operator’s percentage of the total inference time:

gr_dur /= gr_dur['dur'].sum()

dslm-fig-10.6-bar-chart-showing-the-number.png

[!visual-conversion] Figure 10.6 — Number of invocations of the three ONNX operators in the linear regression model’s graph (p. 204)

Now we’ll create a visualization from this data (figure 10.7):

fig = px.bar(gr_dur, x='dur',
labels={
"dur": "Duration (%)",
"args_op_name": "Operation type",
},
title='Proportion')
fig.show()

These three visualizations help us quickly spot opportunities for graph optimization in an ONNX model.

For LLMs, we can reuse the same data-cleaning, aggregation, and visualization code unchanged; a companion Colab notebook is provided. The notebook covers converting the GPT-2 small model to ONNX, running inline profiling, and analyzing and visualizing the profiling data. We won’t repeat the code for loading the model and tokenizer or converting to ONNX because we covered them in earlier chapters. Instead, we’ll just look at the charts produced by profiling the ONNX GPT-2 small model (figures 10.8–10.10).

In figure 10.8, the x-axis shows duration (ms), and the y-axis lists the ONNX operation types in the profiled run.

In figure 10.9, the x-axis shows how many times each ONNX operator was called, and the y-axis lists the operator types used in the profiled run.

In figure 10.10, the x-axis shows the percentage of total inference time, and the y-axis lists the ONNX operation types in the profiled run.

dslm-fig-10.7-bar-chart-showing-the-percentage.png

[!visual-conversion] Figure 10.7 — Percentage of total inference time for each ONNX operator call in the linear regression model (p. 205)

dslm-fig-10.8-bar-chart-showing-the-total.png

[!visual-conversion] Figure 10.8 — Total duration (ms) of ONNX operators in the GPT-small linear regression model’s graph during profiling (p. 205)

dslm-fig-10.9-bar-chart-showing-onnx-operator.png

[!visual-conversion] Figure 10.9 — ONNX operator invocation counts in the GPT-2 small model graph (p. 206)

dslm-fig-10.10-bar-chart-showing-the-percentage.png

[!visual-conversion] Figure 10.10 — The percentage of overall inference time for each ONNX operator call in the GPT-2 small model during profiling (p. 206)

The ORT for Python can evaluate models converted to ONNX—not only the full graph, but also individual nodes (including custom ones). It can also capture intermediate results within a graph or node. Converting to a new model version or moving from a Python ML/DL framework to an ONNX graph can introduce inefficiencies, and evaluating one or more nodes can help you find and fix them.

Let’s first consider the simple linear regression example model from section 10.1. To evaluate the model’s full ONNX graph, we can use ONNX’s ReferenceEvaluator class:

from onnx.reference import ReferenceEvaluator
sess = ReferenceEvaluator(onnx_model)

We’ll prepare the model’s input arrays as usual:

import numpy as np
x = np.random.randn(4, 2).astype(np.float32)
a = np.random.randn(2, 1).astype(np.float32)
b = np.random.randn(1, 1).astype(np.float32)
feeds = {'X': x, 'A': a, 'B': b}

Then we’ll run the model using the previously created ReferenceEvaluator instance:

evaluation = sess.run(None, feeds)

We can also evaluate a single node in the graph. For the MatMul node in our regression model, do the following:

node_sess = ReferenceEvaluator(node1)
feeds = {'X': x, 'A': a}
node_evaluation = node_sess.run(None, feeds)

We can enable step-to-step evaluation by setting the verbose argument on a ReferenceEvaluator instance to different levels of verbosity:

sess = ReferenceEvaluator(onnx_model, verbose=verbose)

The verbose argument accepts integer values from 1 (the default, less verbose) to 4 (the most verbose, step-by-step evaluation). For our linear regression model, the following output displays the different verbosity levels:

------ verbose=1

[array([[0.9837985],
[1.126987 ],
[0.8049259],
[1.6867123]], dtype=float32)]
------ verbose=2
MatMul(X, A) -> XA
Add(XA, B) -> Y
[array([[0.31629467],
[1.5107596 ],
[1.008173 ],
[1.2464874 ]], dtype=float32)]
------ verbose=3
+I X: float32:(4, 2) in [-0.8688125014305115, 0.7680516242980957]
+I A: float32:(2, 1) in [0.6488013863563538, 1.9162827730178833]
+I B: float32:(1, 1) in [2.00530743598938, 2.00530743598938]
MatMul(X, A) -> XA
+ XA: float32:(4, 1) in [-1.2202415466308594, 1.2917602062225342]
Add(XA, B) -> Y
+ Y: float32:(4, 1) in [0.7850658893585205, 3.297067642211914]
[array([[2.835943 ],
[3.2970676],
[1.3345237],
[0.7850659]], dtype=float32)]
------ verbose=4
+I X: float32:(4, 2):1.4935364723205566,-
0.163960694179535,1.1996209621429443,-0.47337841987609863,-
2.4281582832336426...
+I A: float32:(2, 1):[0.8013423681259155, -0.34330955147743225]
+I B: float32:(1, 1):[-1.6645238399505615]
MatMul(X, A) -> XA
+ XA: float32:(4, 1):[1.253123164176941, 1.1238224506378174,
-2.082425594329834, -0.8871934413909912]
Add(XA, B) -> Y
+ Y: float32:(4, 1):[-0.4114006757736206, -0.5407013893127441,
-3.7469494342803955, -2.5517172813415527]
[array([[-0.41140068],
[-0.5407014 ],
[-3.7469494],
[-2.5517173 ]], dtype=float32)]

As the previous code shows, verbosity level 1 displays only the model’s output, level 2 also shows the sequence of operations between inputs, level 3 also includes input values and intermediate outputs, and level 4 includes the inputs to the intermediate steps.

The linear regression in this example follows this formula:

y=Add(MatMul(X,A),B)y = \text{Add}(\text{MatMul}(X, A), B)

Another way to implement linear regression is to use a similar formula, adding the identity matrix to matrix A:

y=Add(MatMul(X,Add(A,I)),B)y = \text{Add}(\text{MatMul}(X, \text{Add}(A, \mathbf{I})), B)

To implement it, you’ll need to modify the original code that builds the model with ONNX operators:

node0 = make_node('EyeLike', ['A'], ['Eye'])
node1 = make_node('Add', ['A', 'Eye'], ['A1'])
node2 = make_node('MatMul', ['X', 'A1'], ['XA1'])
node3 = make_node('Add', ['XA1', 'B'], ['Y'])
graph = make_graph([node0, node1, node2, node3], 'lr', [X, A, B], [Y])

In this example, we use the EyeLike operator, ONNX’s implementation of the identity matrix (a square matrix with ones on the main diagonal and zeros elsewhere), and combine the nodes to build the final graph for the updated linear regression formula.

As mentioned earlier in this section, you can also evaluate custom ONNX nodes. For example, in the following code, we’ll create a custom node that combines the EyeLike and Add operators and then see whether the model runs more efficiently:

node01 = make_node('AddEyeLike', ['A'], ['A1'], domain='combined')

We can then rebuild the graph:

node2 = make_node('MatMul', ['X', 'A1'], ['XA1'])
node3 = make_node('Add', ['XA1', 'B'], ['Y'])
graph = make_graph([node01, node2, node3], 'lr', [X, A, B], [Y])

Let’s rebuild the model and recheck it:

from onnx.helper import make_opsetid
onnx_optimized_model = make_model(graph, opset_imports=[
make_opsetid('', 18), make_opsetid('combined', 1)
])
check_model(onnx_optimized_model)

This kind of optimization—combining two operators into a single optimized operator (AddEyeLike)—is called fusion. To evaluate the custom node (or a model whose graph includes it), you must implement a custom class, because ReferenceEvaluator natively supports only built-in ONNX operators. However, it can also accept custom operator implementations. You can implement custom operators by extending the ONNX OpRun class and implementing its _run method:

from onnx.reference.op_run import OpRun
class AddEyeLike(OpRun):
op_domain = "combined"
def _run(self, X, alpha=1.):
assert len(X.shape) == 2
assert X.shape[0] == X.shape[1]
X = X.copy()
ind = numpy.diag_indices(X.shape[0])
X[ind] += alpha
return (X,)

You can now evaluate the model as usual. The only difference is that when you create a ReferenceEvaluator instance, you also need to pass a list of the custom node implementations included in the model’s ONNX graph:

sess = ReferenceEvaluator(onnx_optimized_model, verbose=2,
new_ops=[AddEyeLike])

Evaluation for the given inputs proceeds the same way as for models without custom operators:

x = numpy.random.randn(4, 2).astype(numpy.float32)
a = numpy.random.randn(2, 2).astype(numpy.float32) / 10
b = numpy.random.randn(1, 2).astype(numpy.float32)
feeds = {'X': x, 'A': a, 'B': b}
sess.run(None, feeds)

Before measuring any execution speedup, let’s confirm that the optimization didn’t reduce prediction quality. We’ll evaluate both model versions (the original and the one after fusing the two operators):

sess_original = ReferenceEvaluator(onnx_model)
sess_optimized = ReferenceEvaluator(onnx_optimized_model,
new_ops=[AddEyeLike])
y_original = sess_original.run(None, feeds)[0]
y_optimized = sess_optimized.run(None, feeds)[0]
print(f"output from original model: {y_original}")
print(f"output from optimized model: {y_optimized}")
print(f"difference: {numpy.abs(y_original - y_optimized).max()}")

There is no difference:

output from original model: [[-1.3435526 0.11092019]
[ 0.8220897 0.18847765]
[-1.29872 0.882055 ]
[-0.10433175 -0.30559355]]
output from optimized model: [[-1.3435526 0.11092019]
[ 0.8220897 0.18847765]
[-1.29872 0.882055 ]
[-0.10433175 -0.30559355]]

difference: 0.0

Let’s now benchmark both model versions on larger matrices, timing 10,000 runs w/ Python’s timeit package:

x = numpy.random.randn(4, 100).astype(numpy.float32)
a = numpy.random.randn(100, 100).astype(numpy.float32) / 10
b = numpy.random.randn(1, 100).astype(numpy.float32)
feeds = {'X': x, 'A': a, 'B': b}
import timeit
print(f"time with EyeLike+Add: {timeit.timeit(lambda:
sess_original.run(None, feeds), number=10000)}")
print(f"time with AddEyeLike: {timeit.timeit(lambda:
sess_optimized.run(None, feeds), number=10000)}")

There is a clear improvement with the optimized model:

time with EyeLike+Add: 1.1427911999999196
time with AddEyeLike: 0.8636034999999538

You can also evaluate and profile by following the directions in sections 7.1 and 7.2. I ran the benchmarks on a PC with two Intel Core i5-7300U CPUs (2.6 GHz) and 8 GB of RAM.

In section 5.6.1, I described ONNX Runtime (ORT) optimization levels and how they apply to LLMs. You also saw that graph optimization can be done offline or inline, and that ORT provides two optimization sets: basic (including the operator fusion introduced in this section) and extended. I also introduced the built-in optimizer class for Transformer models in the ORT API, which automates offline graph optimization for an ONNX model (or a model converted to ONNX format). Now let’s see how the ONNX graph for an LLM changes after optimization.

In this example, we’ll use the GPT-2 small model; the complete code is in the Colab notebook for section 10.2. No hardware acceleration is required; all optimization considerations are for CPUs only. After downloading the GPT-2 small weights and tokenizer from the Hugging Face Hub and converting the model to ONNX, we can optimize it offline programmatically with the ORT optimizer:

from onnxruntime.transformers import optimizer
num_layer = model.config.n_layer
num_attention_heads = model.config.n_head
hidden_size = model.config.n_embd
onnx_model_path='gpt2onnx.onnx'
onnx_optim_model_path="gpt2onnx-opt.onnx"
optimized_model = optimizer.optimize_model(onnx_model_path,
model_type='gpt2',
num_heads=num_attention_heads,
hidden_size=hidden_size,
use_gpu=False,
opt_level=1,
verbose=True)
optimized_model.convert_float_to_float16()
optimized_model.save_model_to_file(onnx_optim_model_path)

We provided the optimizer with the original ONNX model location, model architecture type, number of attention heads, hidden size, lack of hardware acceleration, and optimization level (1, which applies only basic graphic optimizations). After optimization, the model is about half the size of the original (309 MB vs. 622 MB). The optimizer also applied several basic optimizations, such as removing 108 nodes (mainly unnecessary Reshape nodes), as shown in figure 10.11, which compares the original ONNX graph with the optimized graph’s input layers.

dslm-fig-10.11-comparing-the-input-layers-of.png

[!visual-conversion] Figure 10.11 — Comparing the input layers of the GPT-2 ONNX-converted model’s graph before and after optimization (p. 212)

The optimizer also applied some extended optimizations—such as Skip Layer Normalization Fusion (which fuses fully connected layer biases, skip connections, and layer normalizations; see figure 10.12)—because we’ve specified the model architecture (a decoder-only Transformer).

dslm-fig-10.12-comparing-part-of-the-gpt.png

[!visual-conversion] Figure 10.12 — Comparing part of the GPT-2 ONNX-converted model’s graph, before and after optimization, showing Skip Layer Normalization Fusion applied (p. 213)

In the Netron tool (https://github.com/lutzroeder/netron), you can inspect the optimized graph and see that additional optimizations, such as Fast GELU Fusion, have been applied.

By profiling both versions of the ONNX model, we can see the performance gain (compare figure 10.13 with figures 10.8 and 10.9 for the original ONNX GPT-2 model).

dslm-fig-10.13-counts-and-durations-for-each.png

[!visual-conversion] Figure 10.13 — Counts and durations for each ONNX operator in the optimized GPT-2 model graph (p. 214)

Summary

Analyzing the automated ONNX optimizations for LLMs is a great way to learn where and how to apply them manually to custom models.

This chapter wraps up our exploration of the ONNX format and ORT. The next two chapters show how you can combine these and other techniques from earlier chapters with SLM deployment in diverse environments to make the most of available computational power without sacrificing too much quality.

  • Enable performance profiling in ONNX Runtime (ORT) by setting enable_profiling to True in SessionOptions.

  • Raw profiling data is stored in JSON files with timing information for each operator execution.

  • OnnxWholeSession.process_profiling converts messy JSON profiling output into a clean, tabular DataFrame format.

  • Plotly Express can create interactive bar charts of operator duration, call counts, and execution percentages for performance analysis.

  • The ReferenceEvaluator class evaluates entire ONNX models or individual nodes for debugging and optimization.

  • Verbosity levels 1 to 4 control how much step-by-step evaluation detail you see when debugging.

  • Operator fusion combines consecutive operators into single optimized nodes to speed execution.

  • To evaluate custom operators, extend the OpRun class, and implement _run.

  • The ORT optimizer automatically applies basic and extended optimizations to transformer models.

  • Graph optimization reduces model size by removing unnecessary nodes, such as redundant Reshape operations.

  • Skip Layer Normalization Fusion combines bias layers, skip connections, and layer normalizations into single operations.

  • Fast GELU Fusion optimization is applied automatically when you specify the model’s architecture type.

  • The Netron tool lets you visually inspect ONNX graphs to see which optimizations were applied.

  • Model evaluation ensures optimizations don’t hurt prediction quality or accuracy.

  • Basic optimizations include constant folding, eliminating redundant nodes, and semantics-preserving fusions.

  • Extended optimizations perform complex node fusions specific to CPU, CUDA, or ROCm execution providers.