Skip to main content

Transformers Tools

ONNX Runtime provides specialized tools for optimizing transformer-based models including BERT, GPT-2, T5, BART, and other popular architectures. These tools apply graph transformations to fuse operators and improve performance.

Optimizer

optimize_model()

Optimize transformer models with architecture-specific fusions.
str | ModelProto
required
Path to ONNX model file or ModelProto object.
str
Model architecture type. Supported values:
  • “bert” - BERT and variants (default)
  • “gpt2” - GPT-2, GPT-Neo
  • “bart” - BART models
  • “t5” - T5 models
  • “clip” - CLIP vision/text models
  • “unet” - UNet (Stable Diffusion)
  • “vae” - VAE (Stable Diffusion)
  • “phi” - Phi models
int
Number of attention heads. Auto-detected if 0.
int
Hidden layer size. Auto-detected if 0.
FusionOptions
Options controlling which optimizations to apply.
int
Optimization level (0-2). Higher levels apply more aggressive optimizations.
bool
Whether the model will run on GPU. Enables GPU-specific optimizations.
bool
Use only ORT built-in optimizations without custom graph transformations.
OnnxModel
Optimized model object that can be saved to file.

Model Types

Supported Architectures

str
BERT, RoBERTa, DistilBERT, ALBERT, ELECTRA, DeBERTa, and similar encoder models.
str
GPT-2, GPT-Neo, GPT-J, and other autoregressive decoder models.
str
T5, mT5, and encoder-decoder models.
str
BART, mBART, and similar sequence-to-sequence models.
str
CLIP vision and text encoders.
str
UNet models from Stable Diffusion.
str
VAE encoder/decoder from Stable Diffusion.

Example Usage

Basic BERT Optimization

GPU Optimization

Custom Optimization Options

T5 Model Optimization

Float16 Conversion

Fusion Options

FusionOptions

Controls which graph fusions to apply.

Optimization Levels

int
Basic optimizations only. Minimal transformations.
int
Standard optimizations. Applies common fusions (default for most models).
int
Aggressive optimizations. Maximum fusions and transformations.

Benchmark Helper

Quantization for Transformers

Model Analysis

Export Utilities

Large Model Exporter

IO Binding Helper

Machine Info

Best Practices

Complete Optimization Pipeline