liveBook · Manning

Transformer optimizer

As explained in Domain-Specific Small Language Models

An ONNX Runtime optimization component that rewrites Transformer-style graphs for better inference performance.

The ONNX Runtime Transformer optimizer rewrites converted Transformer graphs to improve inference performance. It automates graph optimization, avoiding manual inspection as a first resort. section 5.6.1 section 10.3

Optimization levels trade off the scope of graph rewrites:

  • Basic optimization folds constants, removes redundant nodes, and applies semantics-preserving fusions. section 5.6.1
  • Extended optimization applies more complex fusions to nodes assigned to CPU, CUDA, or ROCm providers. section 5.6.1
  • Layout optimization changes data layout for applicable nodes assigned to the CPU provider. section 5.6.1

GPT-2 graph optimization

For GPT-2 small on CPU, basic optimization removed 108 nodes, mainly unnecessary Reshape nodes, and reduced the model from 622 MB to 309 MB. The optimizer also applied Skip Layer Normalization Fusion. section 10.3

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)

Example call for optimizing a GPT-2 ONNX model on CPU, then converting it to float16 and saving it. section 10.3

How Domain-Specific Small Language Models covers it

How deep it goes
Explains optimization levels and graph rewrites, including provider limits, without detailing optimizer internals.
Examples
Demonstrates GPT-2 optimization, node removal, model-size reduction, and Skip Layer Normalization Fusion.
What it assumes
Assumes a converted ONNX model and, for the Transformer optimizer, the architecture type, attention-head count, and hidden size.
What you can do after
Apply optimization through ONNX Runtime to a converted model offline or configure graph optimization during inference-session initialization.
How it connects
Connects ONNX Runtime graph optimization with ONNX models, inference, and Transformer architectures such as GPT-2.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Domain-Specific Small Language Models. The section links point to the parts of the book it draws on.