import sys
import torch
import torch.onnx
from collections import OrderedDict
sys.path.append(r"./pycls")
from pycls.models.effnet import EffNet
import pycls.core.config as config
from pycls.core.config import cfg
def proc_node_module(checkpoint, attr_name):
new_model_state = OrderedDict()
for k, v in checkpoint[attr_name].items():
if (k[0: 7] == "module."):
name = k[7:]
else:
name = k[0:]
new_model_state[name] = v
return new_model_state
def convert(input_file_, yaml_file_, output_file_):
config.load_cfg(yaml_file_)
cfg.freeze()
model = EffNet()
checkpoint = torch.load(input_file_, map_location='cpu')
checkpoint['model_state'] = proc_node_module(checkpoint, 'model_state')
model.load_state_dict(checkpoint["model_state"])
model.eval()
input_names = ["image"]
output_names = ["class"]
dynamic_axes = {'image': {0: '-1'}, 'class': {0: '-1'}}
dummy_input = torch.randn(1, 3, 240, 240)
torch.onnx.export(model, dummy_input, output_file_, input_names=input_names, dynamic_axes=dynamic_axes,
output_names=output_names, opset_version=11, verbose=True)
if __name__ == "__main__":
input_file = sys.argv[1]
yaml_file = sys.argv[2]
output_file = sys.argv[3]
convert(input_file, yaml_file, output_file)