tutorials icon indicating copy to clipboard operation
tutorials copied to clipboard

.pth to .onnx

Open yuxiazff opened this issue 7 years ago • 3 comments

i have a pytorch model xxxx.pth, but inside there is only parameters, and no the structure of the model. can it be translate to .onnx file ? how ? i used the code to load the model:

model=torch.load(model_pth_path) print type(model) dummy_input = Variable(torch.randn(1, *input_shape)) output = torch_onnx.export(model,dummy_input,model_onnx_path,verbose=True) print("Export of torch_model.onnx complete!")

but it report an error:

Traceback (most recent call last): File "convert_to_onnx.py", line 31, in output = torch_onnx.export(model,dummy_input,model_onnx_path,verbose=True) File "/usr/local/lib/python2.7/dist-packages/torch/onnx/init.py", line 26, in export return utils.export(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/torch/onnx/utils.py", line 94, in export operator_export_type=operator_export_type) File "/usr/local/lib/python2.7/dist-packages/torch/onnx/utils.py", line 226, in _export example_outputs, propagate) File "/usr/local/lib/python2.7/dist-packages/torch/onnx/utils.py", line 177, in _model_to_graph graph, torch_out = _trace_and_get_graph_from_model(model, args, training) File "/usr/local/lib/python2.7/dist-packages/torch/onnx/utils.py", line 136, in _trace_and_get_graph_from_model orig_state_dict_keys = _unique_state_dict(model).keys() File "/usr/local/lib/python2.7/dist-packages/torch/jit/init.py", line 81, in _unique_state_dict state_dict = module.state_dict(keep_vars=keep_vars) AttributeError: 'OrderedDict' object has no attribute 'state_dict'

yuxiazff avatar Oct 22 '18 09:10 yuxiazff

torch.onnx need both the architure and the parameters. You should define the network before load xxx.pth.

fwz-fpga avatar Oct 26 '18 10:10 fwz-fpga

I have the same problem,it need architure, as follows: 【My code】 import torch from torch.autograd import Variable from backbone.resnet import get_pose_net from backbone.vovnetv2 import VoVNet39_slim

output_onnx = 'centernet.onnx' pytorch_model = 'net_resume.pth'

model = VoVNet39_slim(eSE=False) #model.cuda() model.load_state_dict(torch.load(pytorch_model)) model.train(False) dummy_input = Variable(torch.randn(1, 3, 416, 416)).cpu() torch.onnx.export(model, dummy_input, output_onnx, verbose = True, input_names = ['data'], output_names = ['hm', 'reg', 'wh'])

ruabuliuqiu avatar Aug 05 '20 02:08 ruabuliuqiu

I have the same problem,how to modify it。。

torch.onnx need both the architure and the parameters. You should define the network before load xxx.pth.

Yes,you are right, acording to your guidance,it works,thanks

ruabuliuqiu avatar Aug 05 '20 07:08 ruabuliuqiu