当前位置:网站首页>General code for pytorch model to libtorch and onnx format
General code for pytorch model to libtorch and onnx format
2022-08-02 15:26:00 【Hongyao】
依赖
- torch
- onnx
- onnx simplifer
Important parameters that need to be set by yourself
- model_path 模型权重路径
- model 网络实例
- inp 样例输入,就是一个shape合法的tensor,batchsize(第一维)设置为1就行
下面以torchvision自带的resnet101模型为例.The weights are using the official pretrained model,调用resnet101(pretrained=True)will be downloaded automatically%USERPROFILE%/.cache/torch/hub下面
import onnx
import torch
from torch.utils.mobile_optimizer import optimize_for_mobile
from torchvision.models.resnet import resnet101
from utils.func import file_size, colorstr
model_path = './weights/resnet101.pth' # 模型权重路径
model = resnet101() # 模型对象
height, width = 640, 640
inp = torch.zeros([1, 3, height, width]) # 样例输入,用于trace
# common
half = True # fp16量化
# onnx profile
onnx_export = True # 是否输出onnx格式
opset_version = 13 # 算子集版本
dynamic = False # Whether to enter dynamicallybatchsize,The following two options need to be set
input_names = ['inputs']
dynamic_axes = {
'inputs': {
0: 'batch', 1: 'kp28'}, # 动态batchsize设置
'output': {
0: 'batch', 1: 'classes'}}
simplify = True # whether to simplify
# libtorch profile
libtorch_export = True # 是否输出libtorch格式
optimize = False # 针对移动端优化,Not for mobile use
strict = False # 严格模式,设置False就行
if __name__ == '__main__':
model.load_state_dict(torch.load(model_path))
model.cpu().eval()
if half:
inp, model = inp.half(), model.half()
if onnx_export:
prefix = colorstr('ONNX:')
f = model_path.replace('.pth', '.onnx') # filename
torch.onnx.export(model, inp, f, verbose=False, opset_version=opset_version, input_names=input_names,
training=torch.onnx.TrainingMode.EVAL,
do_constant_folding=True,
dynamic_axes=dynamic_axes if dynamic else None)
# Checks
model_onnx = onnx.load(f) # load onnx model
onnx.checker.check_model(model_onnx) # check onnx model
# print(onnx.helper.printable_graph(model_onnx.graph)) # print
# Simplify
if simplify:
try:
import onnxsim
print(f'simplifying with onnx-simplifier {
onnxsim.__version__}...')
model_onnx, check = onnxsim.simplify(
model_onnx,
dynamic_input_shape=dynamic,
input_shapes={
'images': list(inp.shape)} if dynamic else None)
assert check, 'assert check failed'
onnx.save(model_onnx, f)
except Exception as e:
print(f'{
prefix} simplifier failure: {
e}')
print(f'{
prefix} export success, saved as {
f} ({
file_size(f):.1f} MB)')
if libtorch_export:
prefix = colorstr('TorchScript:')
try:
print(f'\n{
prefix} starting export with torch {
torch.__version__}...')
f = model_path.replace('.pt', '.torchscript.pt') # filename
ts = torch.jit.trace(model, inp, strict=strict)
(optimize_for_mobile(ts) if optimize else ts).save(f)
print(f'{
prefix} export success, saved as {
f} ({
file_size(f):.1f} MB)')
except Exception as e:
print(f'{
prefix} export failure: {
e}')
边栏推荐
- STM32LL库——USART中断接收不定长信息
- 关于c语言的调试技巧
- DP1332E刷卡芯片支持NFC内置mcu智能楼宇/终端poss机/智能门锁
- Binder ServiceManager解析
- Binder机制(中篇)
- 编译error D8021 :无效的数值参数“/Wextra” cl command line error d8021 invalid numeric argument ‘/wextra‘
- Win11 system cannot find dll file how to fix
- 机器学习和深度学习中的梯度下降及其类型
- 基于深度学习的配准框架
- FP7195大功率零压差全程无频闪调光DC-DC恒流芯片(兼容调光器:PWM调光,无极调光,0/1-10V调光)
猜你喜欢
Win10 Settings screen out from lack of sleep?Win10 set the method that never sleep
Win7遇到错误无法正常开机进桌面怎么解决?
Binder机制(下篇)
为android系统添加产品的过程
FP7122降压恒流内置MOS耐压100V共正极阳极PWM调光方案原理图
How to reinstall Win7 system with U disk?How to reinstall win7 using u disk?
PyTorch⑦---卷积神经网络_非线性激活
【STM32学习1】基础知识与概念明晰
基于51单片机和物联网的智能家居系统(ESP8266物联网模块)
Binder ServiceManager解析
随机推荐
pytorch模型转libtorch和onnx格式的通用代码
Do Windows 10 computers need antivirus software installed?
PyTorch⑨---卷积神经网络_线性层
BLE蓝牙5.2-PHY6222系统级芯片(SoC)智能手表/手环
Actual combat Meituan Nuxt +Vue family bucket, server-side rendering, mailbox verification, passport authentication service, map API reference, mongodb, redis and other technical points
Win7遇到错误无法正常开机进桌面怎么解决?
镜像法求解接地导体空腔电势分布问题
Tensorflow张量生成
Win11电脑一段时间不操作就断网怎么解决
How to add a one-key shutdown option to the right-click menu in Windows 11
LORA芯片ASR6505无线远距离传输8位MCU
【我的电赛日记(一)】HMI USART串口屏
Win10安装了固态硬盘还是有明显卡顿怎么办?
ASR6601牛羊定位器芯片GPS国内首颗支持LoRa的LPWAN SoC
2020-02-06-快速搭建个人博客
Daily - Notes
Pytorch(16)---搭建一个完整的模型
win11一直弹出用户账户控制怎么解决
Win11 computer off for a period of time without operating network how to solve
LORA芯片ASR6601支持M4内核的远距离传输芯片