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()
相关推荐
倚肆2 分钟前
Spring Boot 中的 Bean 与自动装配详解
spring boot·后端·python
不剪发的Tony老师3 分钟前
PyScripter:一款免费开源、功能强大的Python开发工具
ide·python
FL171713145 小时前
Pytorch保存pt和pkl
人工智能·pytorch·python
爱学习的小道长7 小时前
进程、线程、协程三者的区别和联系
python·ubuntu
L-李俊漩7 小时前
MMN-MnnLlmChat 启动顺序解析
开发语言·python·mnn
大雷神8 小时前
HarmonyOS 横竖屏切换与响应式布局实战指南
python·深度学习·harmonyos
钅日 勿 XiName8 小时前
一小时速通pytorch之训练分类器(四)(完结)
人工智能·pytorch·python
青瓷程序设计8 小时前
水果识别系统【最新版】Python+TensorFlow+Vue3+Django+人工智能+深度学习+卷积神经网络算法
人工智能·python·深度学习
AI模块工坊9 小时前
CVPR 即插即用 | 当RetNet遇见ViT:一场来自曼哈顿的注意力革命,中科院刷新SOTA性能榜!
人工智能·深度学习·计算机视觉·transformer
*才华有限公司*9 小时前
基于BERT的文本分类模型训练全流程:从环境搭建到显存优化实战
python