Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.

Get Started Now!

Microsoft Open-Sources ONNX Acceleration for BERT AI Model

Microsoft Open-Sources ONNX Acceleration for BERT AI Model
Microsoft Azure Machine Learning

Last updated: 02 December 2026

Microsoft’s open-sourcing of ONNX acceleration for BERT happened in January 2020. The Azure Machine Learning team contributed its BERT inference optimizations to ONNX Runtime. This article covers what was released, what the headline numbers mean, and how to use the same tooling today.

What Microsoft released

The optimizations began in Bing, which had tuned BERT inference on NVIDIA GPUs for its real-time search service. Microsoft then extended the work to CPUs and contributed it to the open-source ONNX Runtime library. Anyone could then run BERT-style models faster without building custom kernels.

The reported results were:

  • CPU: about 17x lower latency on a 3-layer BERT model with a sequence length of 128, at roughly 100 queries per second.
  • GPU: more than 3x lower latency on NVIDIA GPUs, with a batch size of 64 reaching about 10,000 queries per second.

Read the 17x figure carefully

The 17x number is a best case. It was measured on a small 3-layer model, not the standard 12-layer BERT-base, and on one sequence length. Your speedup depends on model size, sequence length, batch size, hardware and the baseline you compare against. Measure on your own workload before you promise anything to stakeholders.

How the acceleration works

ONNX is an open model format. ONNX Runtime executes the exported graph and applies optimizations to it. For transformers, the main gains come from graph-level changes:

  • Operator fusion: several small operations, such as attention, layer normalization and GELU, are combined into fewer, larger kernels. This reduces memory traffic and launch overhead.
  • Constant folding and redundant node removal: work that can be done ahead of time is removed from the inference path.
  • Mixed precision: on GPUs with Tensor Cores, such as V100 or T4, float16 conversion can improve speed further.

Most fusions need an exact subgraph pattern match. If your export produces a different layout, a fusion may silently not apply.

Flow from PyTorch BERT to ONNX export, optimizer, optional fp16 or int8, verification and benchmarking, then deployment
Workflow for accelerating a BERT model with ONNX Runtime

Using it today

The current ONNX Runtime documentation describes an offline transformer optimizer. It is useful when load-time optimizations do not cover your model, when you want float16 on Tensor Core GPUs, or when dynamic input axes block some fusions. The commands below follow the documented options but have not been tested here, so check them against your installed version.

Step 1: install

pip install onnxruntime        # CPU
pip install onnxruntime-gpu    # GPU (needs CUDA and cuDNN)
pip install torch transformers

Step 2: export to ONNX

python - <<'EOF'
import torch
from transformers import AutoModel, AutoTokenizer
name = "bert-base-uncased"
tok = AutoTokenizer.from_pretrained(name)
model = AutoModel.from_pretrained(name).eval()
inputs = tok("hello world", return_tensors="pt")
torch.onnx.export(
    model,
    (inputs["input_ids"], inputs["attention_mask"], inputs["token_type_ids"]),
    "bert.onnx",
    input_names=["input_ids", "attention_mask", "token_type_ids"],
    output_names=["last_hidden_state"],
    dynamic_axes={k: {0: "batch", 1: "seq"} for k in
                  ["input_ids", "attention_mask", "token_type_ids"]},
    opset_version=17,
)
EOF

Step 3: optimize

python -m onnxruntime.transformers.optimizer \
  --input bert.onnx --output bert_opt.onnx \
  --num_heads 12 --hidden_size 768
# add --float16 for Tensor Core GPUs

Step 4: verify and benchmark

The documentation lists a comparison script for BERT models with three inputs, and a performance test script.

python -m onnxruntime.transformers.compare_bert_results \
  --baseline_model bert.onnx --optimized_model bert_opt.onnx \
  --batch_size 1 --sequence_length 128 --samples 100

python -m onnxruntime.transformers.bert_perf_test \
  --model bert_opt.onnx --batch_size 1 --sequence_length 128

Step 5: run inference

import onnxruntime as ort
sess = ort.InferenceSession("bert_opt.onnx",
        providers=["CPUExecutionProvider"])

Options compared

Approach Best for Trade-off
Plain PyTorch Prototyping Usually slowest for serving
ONNX export only Portability, load-time optimizations Some fusions may not apply
ONNX plus transformer optimizer Production CPU or GPU serving Needs verification of outputs
Optimizer plus float16 Tensor Core GPUs Possible small accuracy change

Best practices

  • Use recent PyTorch and Transformers releases. Different export versions can produce different graph layouts, which affects fusion.
  • Always compare optimized and baseline outputs before deploying.
  • Benchmark with your real batch sizes and sequence lengths, not only the defaults.
  • Keep sequence lengths within documented limits. The docs note a maximum of 1024 for most models on the CUDA attention path because of GPU memory.
  • Use the profiler script to find bottlenecks if the speedup is below expectations.

Common mistakes and troubleshooting

  • Wrong head count or hidden size: the optimizer needs the correct --num_heads and --hidden_size. Take them from the model config.
  • Expecting 17x: that figure came from a small model on CPU. A full BERT-base will typically give a different result.
  • Missing GPU libraries: onnxruntime-gpu needs matching CUDA and cuDNN on the system path.
  • No speedup: check whether fusions applied by inspecting the optimized graph for fused attention nodes. A changed export layout is a likely cause.
  • Accuracy drift with float16: test on a validation set, not only a few samples.

Short exercise

  1. Export bert-base-uncased as above.
  2. Run the benchmark on bert.onnx and bert_opt.onnx with batch size 1 and sequence length 128.
  3. Repeat with sequence length 384 and batch size 8.
  4. Record latency for each run and note where the gap between baseline and optimized is largest.

FAQ

Did Microsoft really open-source this?

Yes. The optimizations were contributed to the open-source ONNX Runtime project, as announced in January 2020.

Is the 17x speedup guaranteed?

No. It was a measured result for a 3-layer BERT on CPU at sequence length 128. The GPU result was more than 3x.

Does this work only for BERT?

No. The same optimizer documentation also covers models such as GPT-2 and Longformer, with model-specific requirements.

Do I need a GPU?

No. The CPU path was part of the original announcement. A GPU helps most with large batches and float16.

Is this the same as quantization?

No. The optimizer page covers graph fusion and float16. Int8 quantization is a separate technique in ONNX Runtime and needs its own accuracy checks.

Bottom line

The 2020 release made production-grade BERT optimizations available to everyone through ONNX Runtime. It remains a practical route to lower latency, provided you export carefully, verify outputs and benchmark on your own workload.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x