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
