[ShapeInferenceError] Mismatch between number of source and target dimensions. Source=1 Target=0

本文探讨了将PyTorch模型转换为ONNX时,保留batch_size维度对于避免运行时错误的关键性。作者通过解决维度问题和调整模型输出,解决了ONNXRuntime的ShapeInferenceError,分享了实践经验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Pytorch转ONNX模型正常,但使用onnxruntime加载onnx模型,会输出错误:

onnxruntime.capi.onnxruntime_pybind11_state.Fail: [ONNXRuntimeError] : 1 : FAIL : Exception during loading: /onnxruntime_src/onnxruntime/core/graph/function.cc:420 onnxruntime::FunctionImpl::FunctionImpl(const onnxruntime::Graph&, const NodeIndex&, const onnx::FunctionProto&, const onnxruntime::logging::Logger&) status.IsOK() was false. Resolve subgraph failed:Node (0x2b97890_109) Op (Loop) [TypeInferenceError] Graph attribute inferencing failed: Node:0x2b97890_109 Output:cond [ShapeInferenceError] Mismatch between number of source and target dimensions. Source=1 Target=0

相关issues:https://github.com/microsoft/onnxruntime/issues/1164

从报错的描述,大致可以定位是输出的维度有问题:于是我详细Debug一下模型输出的'boxes', 'scores'的维度变化:

scores输出维度是(1,13375,2),对应(batch_size,num_anchors,num_class)

boxes输出维度是(13375,4),没有batch_size这个维度,这是因为我进行boxes.data.squeeze(0)处理,不小心把batch_size去掉了

于是我修改源代码,保持'boxes', 'scores'都含有batch_size这个维度,变成

scores输出维度是(1,13375,2),对应(batch_size,num_anchors,num_class)

boxes输出维度是(1,13375,4),对应(batch_size,num_anchors,(x,y,cx,cy))

done,重新生成ONNX模型,并使用onnxruntime加载模型,就没有错误了

结论:转换ONNX模型时,输入输出尽量保留batch_size这个维度,尽管batch_size这个维度经常为1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI吃大瓜

尊重原创,感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值