栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

【pytorch】onnx

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【pytorch】onnx

t7 / pth -> onnx

pytorch任意形式的model(.t7、.pth等等)转.onnx全都可以采用固定格式。

完整实现:

def pth2onnx(self, simplify_onnx_sw=True):
    import torch
    os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

    model = torch.nn.DataParallel(self.model)
    _state_dict = torch.load(pth_path, map_location=torch.device('cpu'))
    model.load_state_dict(_state_dict, strict=True)
    model.eval()
    torch.onnx.export(model.module,
                      torch.randn(batch_size, *C.input_shape),
                      pure_onnx_path,
                      input_names=["input"],
                      output_names=["output"]
                      )

    if simplify_onnx_sw:
        os.system('python -m onnxsim {} {}'.format(pure_onnx_path, simplified_onnx_path))
        print('n Simplified onnx has been save to {}n'.format(simplified_onnx_path))
        os.remove(pure_onnx_path)
    else:
        print('n Pure onnx has been save to {}n'.format(pure_onnx_path))

实验举例:

model_dir = './'
pth_path = model_dir + 'A.pth'
onnx_path = model_dir + 'A.onnx'
batch_size = 1
input_shape = (3, 112, 112)

cfg = Config()
cfg.load_from_file(args.model_cfg_file)

model = PFLD_SE3_eval(cfg.model_conf.layer_cfg, cfg.model_conf.num_points)

model.load(pth_path)
model.eval()
torch.onnx.export(model,
                  torch.randn(batch_size, *input_shape),
                  onnx_path,
                  input_names=["input"],
                  output_names=["output_0", "output_1"],
                  )

print('nn onnx has been save to {}nn'.format(onnx_path))
如在mac下执行,还需要加上这行环境配置: 
os.environ['KMP_DUPLICATE_LIB_OK']='True'

可能的报错:

importError: cannot import name 'get_all_providers' from 'onnxruntime.capi._pybind_state' 

mac下的通用解决方法:

brew install libomp

如果还是报相同错误,则可能是版本问题。换版本即可。例如我是执行:

pip install onnxruntime==1.2.0
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/269563.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号