ML | ONNX Open Neural Network Exchange

ONNX Open Neural Network Exchange

ONNX is an open format built to represent machine learning models. ONNX defines a common set of operators - the building blocks of machine learning and deep learning models - and a common file format to enable AI developers to use models with a variety of frameworks, tools, runtimes, and compilers.

  • ONNX was originally named Toffee and was developed by the PyTorch team at Facebook. In September 2017 it was renamed to ONNX and announced by Facebook and Microsoft. Later, IBM, Huawei, Intel, AMD, Arm and Qualcomm announced support for the initiative.
  • In October 2017, Microsoft announced that it would add its Cognitive Toolkit and Project Brainwave platform to the initiative.
  • In November 2019 ONNX was accepted as graduate project in Linux Foundation AI.
  • In October 2020 Zetane Systems became a member of the ONNX ecosystem.

隨著深度學習技術的發展,越來越多的框架被開發出來以滿足不同的需求。然而,不同的框架之間缺乏互通性可能會限制模型的部署和遷移能力。 Open Neural Network Exchange (ONNX) 格式旨在解決這個問題,它提供了一種標準化的方法來表示機器學習模型,從而實現了不同框架之間的模型轉換和共用。本文將探討如何在不同的深度學習框架之間有效率地轉換和部署模型,並提供一些實際的程式碼範例。

ONNX 是一種開放格式,用於表示機器學習模型,支援各種框架之間的模型轉換。 ONNX 支援多種常見的神經網路結構和操作,包括卷積、池化、活化函數等。透過 ONNX,開發者可以在一個框架中訓練模型,然後將其轉換為 ONNX 格式,最後在另一個框架中載入並執行。

Pytorch

PyTorch export model with ONNX format

1
2
3
4
5
6
7
8
9
10
11
12
PyTorch 匯出模型
import torch
import torchvision.models as models
從 torch.onnx import export

# 載入預先訓練的 ResNet-18 模型
model = models.resnet18(pretrained=True)
model.eval()

# 匯出模型到 ONNX 格式
dummy_input = torch.randn(1, 3, 224, 224)
export(model, dummy_input, "resnet18.onnx", verbose=True, opset_version=11)

Loading ONNX models by PyTorch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import onnxruntime as ort

# 載入 ONNX 模型
ort_session = ort.InferenceSession("resnet18.onnx")

# 預處理輸入數據
data = torch.randn(1, 3, 224, 224).numpy()

# 運行模型
ort_inputs = {
ort_session.get_inputs()[0].name: data}
ort_outs = ort_session.run(None, ort_inputs)

# 輸出預測結果
print("Output:", ort_outs)

最佳實踐

  • 選擇合適的 ONNX 版本:ONNX 不斷更新以支援新的操作和改進效能。選擇最新的 ONNX 版本通常可以獲得更好的支援和效能。
  • 驗證模型轉換:轉換模型後,應確保 ONNX 模型的行為與原生模型一致。可以透過比較兩個模型在相同輸入上的輸出來進行驗證。
  • 檢查模型相容性:不是所有的框架都支援所有 ONNX 操作。確保目標框架支援你的模型中使用的操作。
  • 最佳化模型:在匯出為 ONNX 格式之前,請考慮使用框架提供的工具進行模型最佳化,例如量化、剪枝等。
  • 文件和測試:記錄轉換過程中的重要步驟,並進行充分的測試以確保模型的正確性和效能。

References

  1. https://onnx.ai/
  2. ONNX 模型互操作性的最佳实践
  3. ONNX 與 Azure Machine Learning
  4. 9.1 使用ONNX进行部署并推理

ML | ONNX Open Neural Network Exchange
https://waipangsze.github.io/2024/09/23/ONNX/
Author
wpsze
Posted on
September 23, 2024
Updated on
October 28, 2024
Licensed under