【已解决】YOLO11模型转wts时报错:PytorchStreamReader failed reading zip archive

问题:在把训练好的新YOLO11s模型转wts文件时报错,具体信息如下图(PytorchStreamReader failed reading zip archive: failed finding central directory)

解决:新老版本pytorch之间的兼容问题,改动一下生成wts文件即可。代码帖在下面。

python 复制代码
import sys  # noqa: F401
import argparse
import os
import struct
import torch


def parse_args():
    parser = argparse.ArgumentParser(description='Convert .pt file to .wts')
    parser.add_argument('-w', '--weights', required=True,
                        help='Input weights (.pt) file path (required)')
    parser.add_argument(
        '-o', '--output', help='Output (.wts) file path (optional)')
    parser.add_argument(
        '-t', '--type', type=str, default='detect', choices=['detect', 'cls', 'seg', 'pose', 'obb'],
        help='determines the model is detection/classification')
    args = parser.parse_args()
    if not os.path.isfile(args.weights):
        raise SystemExit('Invalid input file')
    if not args.output:
        args.output = os.path.splitext(args.weights)[0] + '.wts'
    elif os.path.isdir(args.output):
        args.output = os.path.join(
            args.output,
            os.path.splitext(os.path.basename(args.weights))[0] + '.wts')
    return args.weights, args.output, args.type


pt_file, wts_file, m_type = parse_args()

print(f'Generating .wts for {m_type} model')

# Load model
print(f'Loading {pt_file}')

# Initialize
device = 'cpu'

# Load model
model = torch.load(pt_file, map_location=device, weights_only=False)  # Load FP32 weights
model = model['ema' if model.get('ema') else 'model'].float()

if m_type in ['detect', 'seg', 'pose', 'obb']:
    anchor_grid = model.model[-1].anchors * model.model[-1].stride[..., None, None]

    delattr(model.model[-1], 'anchors')

model.to(device).eval()

with open(wts_file, 'w') as f:
    f.write('{}\n'.format(len(model.state_dict().keys())))
    for k, v in model.state_dict().items():
        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')
相关推荐
2601_9571909017 小时前
超元力mr卡丁车:轻量化落地运营,适配中大型场地的新型游乐业态
大数据·人工智能·mr
I"ll carry you17 小时前
【AI应用】使用AI智能体
人工智能·深度学习·ai智能体
牵牛花主人17 小时前
【无标题】
python·pandas
勤自省17 小时前
吴恩达机器学习课程实验:线性回归模型入门(课后实验)
人工智能·算法·机器学习·回归·线性回归
Raink老师17 小时前
【AI面试临阵磨枪-99】纯浏览器 Agent:记忆、工具、RAG、流式、安全如何实现?
人工智能·安全·面试
jimi112617 小时前
从零理解 Transformer
人工智能·深度学习·nlp
abcy07121317 小时前
sqlalchemy 原生sql判断条件是否为空,为空则跳过
开发语言·python
Ada's17 小时前
【解决方案设计】001:类型
人工智能
段一凡-华北理工大学17 小时前
工业领域的Hadoop架构学习~系列文章18:制造业Hadoop应用实践 - 从数据到智能的完整闭环
大数据·人工智能·hadoop·分布式·学习·架构·高炉炼铁
知识分享小能手17 小时前
数据预处理入门学习教程,从入门到精通, 实战演练——数据分析师岗位分析知识点详解(8)
python·学习·信息可视化