zl程序教程

您现在的位置是:首页 >  其它

当前栏目

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

and of number source Target between MISMATCH
2023-09-11 14:17:47 时间

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