Accelerating Model Training with the ONNX Runtime
Tags: machinelearning, deeplearning, azure, onnx
Published: 2020-05-20 10:41:00

---
title: Accelerating Model Training with the ONNX Runtime
published: true
date: 2020-05-20 10:28:12 UTC
tags: machine-learning,deep-learning,azure,onnx
canonical_url: https://medium.com/microsoftazure/accelerating-model-training-with-the-onnx-runtime-519d75a97166
---

![](https://cdn-images-1.medium.com/max/1024/0*9w6EHxtXjGpsZRj-)

TDLR; This article introduces the new improvements to the ONNX runtime for accelerated training and outlines the 4 key steps for speeding up training of an existing pyTorch model with the ONNX Runtime (ORT).

### What is the ONNX Runtime (ORT)?

![](https://cdn-images-1.medium.com/max/1024/0*b9VPseLvwcaMlnnp.png)

**ONNX Runtime** is a performance-focused inference engine for [ONNX (Open Neural Network Exchange) models](https://onnx.ai/). ONNX Runtime was designed with a focus on performance and scalability in order to support heavy workloads in high-scale production scenarios. It also has extensibility options for compatibility with emerging hardware developments.

Recently at [//Build 2020](https://mybuild.microsoft.com/home?WT.mc_id=build2020_ca-medium-abornst&t=%257B%2522from%2522%253A%25222020-05-19T08%253A30%253A00%252B03%253A00%2522%252C%2522to%2522%253A%25222020-05-21T19%253A00%253A00%252B03%253A00%2522%257D), Microsoft announced new capabilities to perform optimized training with the ONNX Runtime in addition to inferencing.

[Announcing accelerated training with ONNX Runtime-train models up to 45% faster - Open Source Blog](https://cloudblogs.microsoft.com/opensource/2020/05/19/announcing-support-for-accelerated-training-with-onnx-runtime/?WT.mc_id=build2020_ca-medium-abornst)

These optimizations led to 45% speed of Microsoft’s own internal Transformer NLP models.

![](https://cdn-images-1.medium.com/max/1024/1*McdpYzQYwtRmC4iDfW8zpQ.png)

As part of our work to give back to the community Microsoft developed an example repo that demonstrates how to integrate ORT training into the official Nvidia [implementation of large BERT model](https://devblogs.nvidia.com/training-bert-with-gpus/) with over _8.3Bn parameters_.

[microsoft/onnxruntime-training-examples](https://github.com/microsoft/onnxruntime-training-examples)

This implementation can be found with the link above and can be even trained on your data using [Azure ML with the example notebook](https://github.com/microsoft/onnxruntime-training-examples/blob/sukha/nvbert/nvidia-bert/azureml-notebooks/run-pretraining.ipynb).

However, while this is amazing for getting started it would be nice to understand what is going on under the hood which can be a little overwhelming at first glance.

In the remainder of this article, I will walk through the 4 main modifications that need to be made to pyTorch models for taking advantage of ORT and point you to where in the example code repo you can deep dive to learn more.

I won’t go through every detail of the modification but I will explain the core concepts so that you can get started on your own ORT journey.

### Step 1: Set Up ORT Distributed Training Environment

To trains large neural networks often requires distributed compute clusters. In this way we can run a version of our script for each GPU on each VM in our cluster. To properly ensure that our data and our model gradients get updated we need to assign each version of our train script with a:

- World Rank — A [rank](https://mpitutorial.com/tutorials/performing-parallel-rank-with-mpi/) for the process across all the VM Instances
- Local Rank — A [rank](https://mpitutorial.com/tutorials/performing-parallel-rank-with-mpi/) for the script process on a given VM Instance

The ort\_supplement provides a setup function that configures the ONNX runtime for distributed training for Open MPI and the Azure Machine Learning Service.

```
device = ort\_supplement.setup\_onnxruntime\_with\_mpi(args)
```

![](https://cdn-images-1.medium.com/max/621/1*aCG8K2rB9EdJ0TJic8y2Kw.png)<figcaption>The Create ORTTrainer function can be found in the<a href="https://github.com/microsoft/onnxruntime-training-examples/blob/sukha/nvbert/nvidia-bert/ort_patch/ort_supplement/ort_supplement.py"> ort_supplement module</a></figcaption>

### Step 2: Create an ORT Trainer Model

Once we have a distributed training environment the next step is to load the pyTorch model into the ORT for training to do this we use the _create\_ort_ trainer method from the ort\_supplement script.

```
model = ort\_supplement.create\_ort\_trainer(args, device, model)
```

![](https://cdn-images-1.medium.com/max/596/1*R67z3n3kI_6gSI-bi8ARRA.png)<figcaption>The Create ORTTrainer function can be found in the<a href="https://github.com/microsoft/onnxruntime-training-examples/blob/sukha/nvbert/nvidia-bert/ort_patch/ort_supplement/ort_supplement.py"> ort_supplement module</a></figcaption>

The ORT Trainer Model requires a couple of important arguments to implement:

1. A **pyTorch model** bundled with a **loss function**
2. **An optimizer function** by default we use the [Lamb Optimizer](https://arxiv.org/abs/1904.00962)
3. A **model description** using the **IODescription** object to explain the model input and output tensor dimensions. Code for an example of the NVIDIA BERT Description looks as follows

![](https://cdn-images-1.medium.com/max/732/1*7xQL9IxIeBWYuwA-ed_taA.png)<figcaption>Note the tensor dimensions should be passed as numeric values to get full optimization benefits</figcaption>

4. **Gradient Accumulation Steps ** — Number of steps to run on a script instance before syncing the gradient

5. **Opset Version — ** The operation set version for the ONNX runtime. The latest version is 12

6. **A** **Post Processing Function (Optional)** that runs after the ONNX runtime converts the pyTorch model to ONNX that can further be used to support unsupported operations and optimize the ONNX model graph further

7. **Map Optimizer Attributes** -maps weight names to a set of optimization parameters.

For more information check out the following resource from the ORT training repo.

[microsoft/onnxruntime](https://github.com/microsoft/onnxruntime/blob/50f798dad6681b5f84ece1a97b4a90504aa330f0/orttraining/orttraining/python/ort_trainer.py)

### Step 3: Call ORT Training Steps to Train Model

Once we’ve initialized our model we need to call **run\_ort\_training\_steps** to actually step forward with our model, calculate it’s local loss and propagate it’s aggregated gradient.

```
loss, global\_step = ort\_supplement.run\_ort\_training\_step(args, global\_step, training\_steps, model, batch) # Runs the actual training steps
```

![](https://cdn-images-1.medium.com/max/725/1*isw6xU4ljh7hAG34V0yuPQ.png)<figcaption>The run_ort_training steps function can be found in the<a href="https://github.com/microsoft/onnxruntime-training-examples/blob/sukha/nvbert/nvidia-bert/ort_patch/ort_supplement/ort_supplement.py"> ort_supplement module</a></figcaption>

### Step 4: Export Trained ONNX Model

Lastly once we have completed all the distributed training iterations of our model. While exporting to ONNX is not mandatory for evaluation doing so enables us to take advantage of ORTs accelerated inferencing. We can export our ORT model to the ONNX format for evaluation by calling the model.save\_as\_onnx function and providing it with our output destination. This function can also be used to checkpoint our model at each epoch.

```
 model.save\_as\_onnx(out\_path)
```

### Conclusion

With the four functions above you have the key tools you need to make sense of the full BERT LARGE ONNX training example. To see them in action check out the [run\_pretraining\_ort](https://github.com/microsoft/onnxruntime-training-examples/blob/master/nvidia-bert/ort_addon/run_pretraining_ort.py) script below.

[microsoft/onnxruntime-training-examples](https://github.com/microsoft/onnxruntime-training-examples/blob/master/nvidia-bert/ort_addon/run_pretraining_ort.py)

### Next Steps

Now that you are more familiar with how to leverage the ORT SDK take a look at some other really cool ONNX blog posts and examples.

- [Accelerate your NLP pipelines using Hugging Face Transformers and ONNX Runtime](https://medium.com/microsoftazure/accelerate-your-nlp-pipelines-using-hugging-face-transformers-and-onnx-runtime-2443578f4333)
- [ONNX: high-perf, cross platform inference - Azure Machine Learning](https://docs.microsoft.com/en-us/azure/machine-learning/concept-onnx?WT.mc_id=build2020_ca-medium-abornst)
- [Evaluating Deep Learning Models in 10 Different Languages (With Examples)](https://dev.to/azure/evaluating-deep-learning-models-in-10-different-languages-with-examples-3b4b)

As the Runtime matures we are always looking for more contributors check out our contribution guidelines here. Hope this helps you on your journey to more efficient deep learning.

### About the Author

[**Aaron (Ari) Bornstein**](https://www.linkedin.com/in/aaron-ari-bornstein-22aa7a77/) is an AI researcher with a passion for history, engaging with new technologies and computational medicine. As an Open Source Engineer at Microsoft’s Cloud Developer Advocacy team, he collaborates with Israeli Hi-Tech Community, to solve real world problems with game changing technologies that are then documented, open sourced, and shared with the rest of the world.

* * *