resnet18下载与保存,转换为ONNX模型,导出 .wts 格式的权重文件

1.download and save to 'resnet18.pth' file:

复制代码
import torch
from torch import nn
from torch.nn import functional as F
import torchvision

def main():
    print('cuda device count: ', torch.cuda.device_count())
    net = torchvision.models.resnet18(pretrained=True)
    #net.fc = nn.Linear(512, 2)
    net = net.to('cuda:0')
    net.eval()
    print(net)
    tmp = torch.ones(2, 3, 224, 224).to('cuda:0')
    out = net(tmp)
    print('resnet18 out:', out.shape)
    torch.save(net, "resnet18.pth")

if __name__ == '__main__':
    main()

this 'resnet18.pth' file contains the model structure and weights.

2.load the .pth file and transform it to ONNX format:

复制代码
import torch

def main():
    
    model = torch.load('resnet18.pth')
    # model.eval()
    inputs = torch.randn(1,3,224,224)
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    inputs = inputs.to(device)
    torch.onnx.export(model,inputs, 'resnet18_trtpose.onnx',training=2)
    
if __name__ == '__main__':
    main()

3.load and read the .pth file, extract the weights of the model to a .wts file

复制代码
import torch
from torch import nn
import torchvision
import os
import struct
from torchsummary import summary

def main():
    print('cuda device count: ', torch.cuda.device_count())
    net = torch.load('resnet18.pth')
    net = net.to('cuda:0')
    net.eval()
    print('model: ', net)
    #print('state dict: ', net.state_dict().keys())
    tmp = torch.ones(1, 3, 224, 224).to('cuda:0')
    print('input: ', tmp)
    out = net(tmp)
    print('output:', out)

    summary(net, (3,224,224))
    #return
    f = open("resnet18.wts", 'w')
    f.write("{}\n".format(len(net.state_dict().keys())))
    for k,v in net.state_dict().items():
        print('key: ', k)
        print('value: ', v.shape)
        vr = v.reshape(-1).cpu().numpy()
        f.write("{} {}".format(k, len(vr)))
        for vv in vr:
            f.write(" ")
            f.write(struct.pack(">f", float(vv)).hex())
        f.write("\n")

if __name__ == '__main__':
    main()
相关推荐
用户0332126663671 分钟前
使用 Python 将 PDF 转换为 Word(转换单个与多个文件)
python
troy1285 分钟前
Visual Studio Code 详细教程:从入门到高效开发
开发语言·python
夜雪一千12 分钟前
Python ASR音频转文本 完整代码示例
python
JarmanYuo23 分钟前
YOLO 涨点研究(十二):具身 CV 进阶篇——Sim2Real 域随机化与真机部署
人工智能·pytorch·python·yolo·计算机视觉
懒羊羊吃辣条26 分钟前
Apache IoTDB 实战测试文档+TimechoDB+Workbench+TS file Viewer+Grafana
人工智能·深度学习·时间序列
小蒜学长30 分钟前
基于Python的微博热搜话题可视化分析系统的设计与实现(代码+数据库+LW)
后端·python·django·数据可视化·情感分析·微博热搜
梦帮科技34 分钟前
从提示词到可复现音乐工作流:RNOISE 2.0 的 Prompt Engineering 架构
人工智能·python·mysql·ci/cd·架构·node.js·numpy
飞Link36 分钟前
【Numpy】 第三部分:矩阵运算与线性代数(计算篇)
python·numpy
电商API_1800790524737 分钟前
电商平台数据分析实战_帖子
开发语言·爬虫·python·数据采集·京东
带多刺的玫瑰1 小时前
Leecode#35刷题之搜索插入位置
java·python·算法