How to Convert Hugging Face Transformers Models to ONNX: A Comprehensive Guide
In the realm of modern machine learning, the ability to convert models into different formats is crucial for deployment and compatibility across various platforms. One such format, the Open Neural Network Exchange (ONNX), allows for interoperability between different frameworks. This article will guide you through three distinct methods to convert the distilbert-base-uncased-finetuned-sst-2-english model from Hugging Face Transformers to ONNX. Whether you’re a seasoned developer or just getting started, you’ll find these methods accessible and straightforward.
Method 1: Export with torch.onnx (Low-Level)
The first approach utilizes the low-level torch.onnx API, which gives you granular control over the export process. While this method requires providing detailed parameters, it’s beneficial for those who want to understand the intricacies of model conversion.
Step-by-step Instructions
-
Install Required Dependencies:
Before starting, ensure you have the necessary packages installed. Run the following command:pip install transformers torch -
Exporting the Model:
Use the following code to export your model:import torch from transformers import AutoModelForSequenceClassification, AutoTokenizer model_id = "distilbert-base-uncased-finetuned-sst-2-english" model = AutoModelForSequenceClassification.from_pretrained(model_id) tokenizer = AutoTokenizer.from_pretrained(model_id) dummy_model_input = tokenizer("This is a sample", return_tensors="pt") torch.onnx.export( model, tuple(dummy_model_input.values()), f="torch-model.onnx", input_names=['input_ids', 'attention_mask'], output_names=['logits'], dynamic_axes={ 'input_ids': {0: 'batch_size', 1: 'sequence'}, 'attention_mask': {0: 'batch_size', 1: 'sequence'}, 'logits': {0: 'batch_size', 1: 'sequence'} }, do_constant_folding=True, opset_version=13, )
This approach provides maximum flexibility but also requires a deeper understanding of the input and output specifications.
Method 2: Export with transformers.onnx (Mid-Level)
For those who prefer a middle ground between low-level control and user-friendliness, the transformers.onnx API is the way to go. This method leverages configuration objects, simplifying complex parameters like dynamic_axes.
Step-by-step Instructions
-
Install Required Dependencies:
You need to install additional dependencies for thetransformers.onnxfunctionality:pip install transformers[onnx] torch -
Exporting the Model:
Use the following code snippet to perform the export:from pathlib import Path import transformers from transformers.onnx import FeaturesManager from transformers import AutoConfig, AutoTokenizer, AutoModelForSequenceClassification model_id = "distilbert-base-uncased-finetuned-sst-2-english" feature = "sequence-classification" model = AutoModelForSequenceClassification.from_pretrained(model_id) tokenizer = AutoTokenizer.from_pretrained(model_id) model_kind, model_onnx_config = FeaturesManager.check_supported_model_or_raise(model, feature=feature) onnx_config = model_onnx_config(model.config) onnx_inputs, onnx_outputs = transformers.onnx.export( preprocessor=tokenizer, model=model, config=onnx_config, opset=13, output=Path("trfs-model.onnx") )
This method abstracts much of the complexity while still providing robust functionality for exporting your model.
Method 3: Export with Optimum (High-Level)
If you’re looking for the most straightforward way to convert your Hugging Face Transformers model to ONNX, the Optimum library is your best bet. This high-level API is designed to simplify the conversion process, making it accessible for users of all skill levels.
Step-by-step Instructions
-
Install Required Dependencies:
To use the Optimum library, install the following:pip install optimum[onnxruntime] -
Exporting the Model:
Here’s how to leverage the high-level API for exporting:from optimum.onnxruntime import ORTModelForSequenceClassification model = ORTModelForSequenceClassification.from_pretrained("distilbert-base-uncased-finetuned-sst-2-english", from_transformers=True)
The beauty of this approach lies in its simplicity. You can immediately use the converted model to run predictions or integrate it into your application without further configuration.
By following these methods, you can effectively convert Hugging Face Transformers models to the ONNX format, ensuring compatibility and flexibility in your machine learning projects. Whether you choose the low-level torch.onnx, the mid-level transformers.onnx, or the high-level Optimum, each method serves a unique purpose tailored to different user needs.
Inspired by: Source

