diff --git a/modules/dnn/src/onnx/onnx_importer2.cpp b/modules/dnn/src/onnx/onnx_importer2.cpp index 4e33cf59e1..d028e054ce 100644 --- a/modules/dnn/src/onnx/onnx_importer2.cpp +++ b/modules/dnn/src/onnx/onnx_importer2.cpp @@ -2604,12 +2604,17 @@ void ONNXImporter2::parseQConv(LayerParams& layerParams, const opencv_onnx::Node Mat bias_float; bias_int32.convertTo(bias_float, CV_32F); + CV_CheckGE(x_scale_mat.total(), (size_t)1, "DNN/ONNX/QLinearConv: x_scale is empty"); float x_sc = x_scale_mat.at(0); if (w_scale_mat.total() == 1) bias_float *= x_sc * w_scale_mat.at(0); else + { + CV_CheckEQ(w_scale_mat.total(), bias_float.total(), + "DNN/ONNX/QLinearConv: per-channel w_scale length must match the bias length"); for (int i = 0; i < (int)w_scale_mat.total(); i++) bias_float.at(i) *= x_sc * w_scale_mat.at(i); + } bias_arg = netimpl->newConstArg(bn + "/bias_float", bias_float); } diff --git a/modules/dnn/test/test_onnx_importer.cpp b/modules/dnn/test/test_onnx_importer.cpp index 7fc8b2ae6d..755ff1f907 100644 --- a/modules/dnn/test/test_onnx_importer.cpp +++ b/modules/dnn/test/test_onnx_importer.cpp @@ -3897,4 +3897,26 @@ INSTANTIATE_TEST_CASE_P(/**/, Test_ONNX_MHA_Lowering, testing::Values( "multi_head_attention_key_padding_mask_attention_bias" )); +// QLinearConv folds a const int32 bias to float by multiplying each bias element +// by the matching per-channel weight scale, writing into a buffer sized from the +// bias tensor. w_scale and the bias are independent model fields, so a w_scale +// longer than the bias wrote past the bias buffer during import. The mismatched +// pair has to be rejected instead of overrunning the buffer. +// Test data in opencv_extra under the same branch name as this patch. +TEST(Test_ONNX_importer, parse_qconv_bias_scale_mismatch) +{ + Net net; + EXPECT_NO_THROW(net = readNetFromONNX(_tf("models/qconv_bias_scale_mismatch.onnx"))); + EXPECT_TRUE(net.empty()); +} + +// The same bias fold reads the scalar x_scale unconditionally, so an empty +// x_scale has to be rejected instead of being read past its end. +TEST(Test_ONNX_importer, parse_qconv_empty_x_scale) +{ + Net net; + EXPECT_NO_THROW(net = readNetFromONNX(_tf("models/qconv_empty_x_scale.onnx"))); + EXPECT_TRUE(net.empty()); +} + }} // namespace