ONNX is an open standard format that allows interoperability of models across different platforms. With ONNX Runtime, you can execute these models efficiently in various deployment scenarios.
Installing ONNX and ONNX Runtime
Begin by installing both ONNX and the ONNX Runtime. For this demo, we assume that the required modules are already installed. If you encounter any issues, install the modules using pip and restart your notebook.Loading and Modifying the Model
In this section, we import the necessary modules from PyTorch and TorchVision to load and modify a MobileNet V3 Large model. After loading the model with pretrained weights, we adjust the classifier’s final layer to output two classes. We then load a checkpoint to restore the model’s state.Exporting the Model to ONNX
PyTorch offers built-in support to export models to the ONNX format. By using the export function, we define the model’s input signature and create an ONNX file. Start by displaying the documentation for torch.onnx.export for available options:Examining the Export Process
For clarity, the following example reiterates the export process: preparing an example input, exporting the model, and verifying the exported ONNX model.Preparing an Image for Inference
Before running inference on the ONNX model, the input image must be preprocessed. This involves resizing, normalizing, and converting the image to a tensor using Pillow and TorchVision transformations. The transformed image is then reshaped to include a batch dimension.Running Inference with ONNX Runtime
With the ONNX model prepared and the input image transformed, we can perform inference using ONNX Runtime. The process involves loading the model, creating an inference session, and using an input dictionary for the session run.Mapping the Prediction to a Label
To present the inference result in a human-friendly format, we associate the numerical prediction with a corresponding class label. Here, the two classes are defined as “malignant” (0) and “benign” (1).
Conclusion
In this demo, we explored the end-to-end process of working with ONNX and ONNX Runtime. We covered the following steps:This guide provides a solid foundation for integrating ONNX models in a variety of deployment environments. For additional information, explore the ONNX Documentation.