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()
相关推荐
范中勤9 分钟前
Python Asyncio 协程与 LLM 异步并发原理技术文档(与 Java 对比|彻底澄清所有误区)
python·llm·协程·并发编程·asyncio
Dmz丶10 分钟前
前端转 AI 100 天 Day 21:FastAPI 入门——从命令行到 HTTP 服务
python
QQ142207844911 分钟前
基于 Flask 的「自动任务控制台」设计与踩坑实录
后端·python·flask
吴佳浩 Alben15 分钟前
一文讲透推理引擎性能指标:TTFT、TPOT、KV命中率、并发,到底对应 vLLM / SGLang 的哪个参数?
人工智能·python·语言模型·架构·ai编程·vllm·sglang
用户2986985301416 分钟前
Python 实现 Word 转 XPS、PostScript 与 OFD 格式
后端·python·api
EasyGBS16 分钟前
社区、校园安防难统一?国标GB28181公网平台EasyGBS视频系统,打破安全监管难题!
深度学习·安全·自动化
陈嘿萌21 分钟前
CVPR 2026 | 全新的五模态信息融合数据集,包括RGB、事件、热成像、4D 雷达与 LiDAR
人工智能·深度学习·计算机视觉·自动驾驶·学术研究与理论基础·点云雷达
Patrick在香港40 分钟前
你写的「比较 token」函数,正在用 36 纳秒泄露密码:时序攻击实测
python·安全·标准库·时序攻击·常量时间
蜗牛互联网41 分钟前
Python Agent 工具调用:审批令牌、参数白名单和累计预算
java·开发语言·人工智能·windows·后端·python
通信大模型1 小时前
VLA模型与世界模型的协同:面向低空无线网络的Embodied Agentic AI 框架
人工智能·深度学习·信息与通信