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()
相关推荐
Dxy12393102168 分钟前
Python XPath position() 完整使用指南,避坑合集(lxml适用)
前端·javascript·python
金融小师妹10 分钟前
多因子智能推演:7月零售销售下降,美元与黄金如何响应的AI传导框架
大数据·深度学习·逻辑回归
AndrewHZ11 分钟前
图像处理入门009 | OpenCV 图像读取与显示:imread/imshow 全解析
图像处理·python·opencv·算法·计算机视觉·图像显示
珐恩AI-人工智能17 分钟前
大模型隐性权重衰减机制剖析:详解GEO长效维稳如何避免优质
大数据·人工智能·深度学习·机器学习·geo优化
卷无止境18 分钟前
手写 SQL 在 Tortoise ORM 里到底能派上什么用场
后端·python·fastapi
龙虾PRO21 分钟前
2026 DeepSeek Harness 部署完整教程:npx 一键启动至 Python SDK 全流程接入
开发语言·python
卷无止境21 分钟前
FastAPI、Tortoise ORM 与 PostgreSQL 三件套 是否好用呢?
后端·python·fastapi
CTA量化套保9 小时前
近期零基础量化学习:先分阶段,再用 AI 检查缺口
人工智能·python
清水白石0089 小时前
Python 死锁排查全攻略:从线程卡死到锁依赖定位与工程化修复
linux·网络·python
Elias不吃糖10 小时前
Langfuse 入门:Trace、Prompt、Dataset、Experiment、Evaluator
前端·python·prompt·langfuse