【已解决】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')
相关推荐
两万五千个小时3 小时前
Agent 记忆不是聊天记录,而是为未来准备的上下文 ——Anthropic 的四层记忆架构与 Dream 思想
人工智能·程序员
汤姆宝库3 小时前
RoPE旋转位置编码的实现与长上下文外推
python·深度学习·机器学习
汤姆宝库3 小时前
语料清洗流水线的实现:启发式过滤、MinHash去重与质量分级
人工智能
火山引擎开发者社区3 小时前
不会 FFmpeg 也能做视频后期?AI MediaKit Skill 帮你实现
人工智能
用户019027581613 小时前
股票代码格式对照:各数据源代码转 AlphaFeed
python
tellmewhoisi3 小时前
深度学习0:数学知识:(L1正则化和L2正则化)
人工智能·深度学习
AI_Gump3 小时前
AutoGLM 两年演进深度解读:一篇讲透智谱的手机 Agent 路线
人工智能·智能手机
玄枢AI3 小时前
AI把待办整理成JSON后,用Python检查漏字段、类型错误和未知值
人工智能
VIP_CQCRE3 小时前
GPT Image 2.6 选型别只看首张:用盲评与合格图耗时比较 Flare、Sunburst
软件测试·图像处理·人工智能
__underline__3 小时前
冷门Python知识点005篇:list.sort( )的排序稳定性,是用0字节额外内存实现的
python·算法