-
Notifications
You must be signed in to change notification settings - Fork 31
/
pytorch2onnx.py
47 lines (39 loc) · 1.54 KB
/
pytorch2onnx.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python3
# coding: utf-8
import argparse
import os.path
from torch.autograd import Variable
import torch.onnx
from BCNN import BCNN
from collections import OrderedDict
def fix_model_state_dict(state_dict):
new_state_dict = OrderedDict()
for k, v in state_dict.items():
name = k
if name.startswith('module.'):
name = name[7:] # remove 'module.' of dataparallel
new_state_dict[name] = v
return new_state_dict
if __name__ == "__main__":
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--trained_model', '-tm', type=str,
help='trained model',
default='checkpoints/mini_instance.pt')
parser.add_argument('--width', type=int,
help='feature map width',
default=672)
parser.add_argument('--height', type=int,
help='feature map height',
default=672)
parser.add_argument('--channel', type=int,
help='feature map channel',
default=6)
args = parser.parse_args()
bcnn_model = BCNN(in_channels=args.channel, n_class=5)
# load it
state_dict = torch.load(args.trained_model)
bcnn_model.load_state_dict(fix_model_state_dict(state_dict))
x = Variable(torch.randn(1, args.channel, args.width, args.height))
torch.onnx.export(bcnn_model, x, os.path.splitext(
args.trained_model)[0] + '.onnx', verbose=True)