1. 程式人生 > 程式設計 >Pytorch模型轉onnx模型例項

Pytorch模型轉onnx模型例項

如下所示:

import io
import torch
import torch.onnx
from models.C3AEModel import PlainC3AENetCBAM

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

def test():
  model = PlainC3AENetCBAM()
 
  pthfile = r'/home/joy/Projects/models/emotion/PlainC3AENet.pth'
  loaded_model = torch.load(pthfile,map_location='cpu')
  # try:
  #   loaded_model.eval()
  # except AttributeError as error:
  #   print(error)

  model.load_state_dict(loaded_model['state_dict'])
  # model = model.to(device)

  #data type nchw
  dummy_input1 = torch.randn(1,3,64,64)
  # dummy_input2 = torch.randn(1,64)
  # dummy_input3 = torch.randn(1,64)
  input_names = [ "actual_input_1"]
  output_names = [ "output1" ]
  # torch.onnx.export(model,(dummy_input1,dummy_input2,dummy_input3),"C3AE.onnx",verbose=True,input_names=input_names,output_names=output_names)
  torch.onnx.export(model,dummy_input1,"C3AE_emotion.onnx",output_names=output_names)

if __name__ == "__main__":
 test()

直接將PlainC3AENetCBAM替換成需要轉換的模型,然後修改pthfile,輸入和onnx模型名字然後執行即可。

注意:上面程式碼中註釋的dummy_input2,dummy_input3,torch.onnx.export對應的是多個輸入的例子。

在轉換過程中遇到的問題彙總

RuntimeError: Failed to export an ONNX attribute,since it's not constant,please try to make things (e.g.,kernel size) static if possible

在轉換過程中遇到RuntimeError: Failed to export an ONNX attribute,kernel size) static if possible的錯誤。

根據報的錯誤日誌資訊開啟/home/joy/.tensorflow/venv/lib/python3.6/site-packages/torch/onnx/symbolic_helper.py,在相應位置新增print之後,可以定位到具體哪個op出問題。

例如:

在相應位置新增

print(v.node())

輸出資訊如下:

%124 : Long() = onnx::Gather[axis=0](%122,%121),scope: PlainC3AENetCBAM/Bottleneck[cbam]/CBAM[cbam]/ChannelGate[ChannelGate] # /home/joy/Projects/models/emotion/WhatsTheemotion/models/cbam.py:46:0

原因是pytorch中的tensor.size(1)方式onnx識別不了,需要修改成常量。

以上這篇Pytorch模型轉onnx模型例項就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。