diff --git a/modules/dnn/include/opencv2/dnn/all_layers.hpp b/modules/dnn/include/opencv2/dnn/all_layers.hpp index 9c2b744cc6..c99b92dc83 100644 --- a/modules/dnn/include/opencv2/dnn/all_layers.hpp +++ b/modules/dnn/include/opencv2/dnn/all_layers.hpp @@ -759,6 +759,12 @@ CV__DNN_INLINE_NS_BEGIN static Ptr create(const LayerParams& params); }; + class CV_EXPORTS DeformConvLayer : public Layer + { + public: + static Ptr create(const LayerParams& params); + }; + class CV_EXPORTS OneHotLayer : public Layer { public: diff --git a/modules/dnn/src/init.cpp b/modules/dnn/src/init.cpp index c526ca85fe..5558c617db 100644 --- a/modules/dnn/src/init.cpp +++ b/modules/dnn/src/init.cpp @@ -149,6 +149,7 @@ void initializeLayerFactory() CV_DNN_REGISTER_LAYER_CLASS(BitShift, BitShiftLayer); CV_DNN_REGISTER_LAYER_CLASS(TensorScatter, TensorScatterLayer); CV_DNN_REGISTER_LAYER_CLASS(GridSample, GridSampleLayer); + CV_DNN_REGISTER_LAYER_CLASS(DeformConv, DeformConvLayer); CV_DNN_REGISTER_LAYER_CLASS(Reduce2, Reduce2Layer); CV_DNN_REGISTER_LAYER_CLASS(NegativeLogLikelihoodLoss, NegativeLogLikelihoodLossLayer); CV_DNN_REGISTER_LAYER_CLASS(SoftmaxCrossEntropyLoss, SoftmaxCrossEntropyLossLayer); diff --git a/modules/dnn/src/layers/deform_conv_layer.cpp b/modules/dnn/src/layers/deform_conv_layer.cpp new file mode 100644 index 0000000000..d7d4ae1c2b --- /dev/null +++ b/modules/dnn/src/layers/deform_conv_layer.cpp @@ -0,0 +1,285 @@ +// This file is part of OpenCV project. +// It is subject to the license terms in the LICENSE file found in the top-level directory +// of this distribution and at http://opencv.org/license.html. + +#include "../precomp.hpp" +#include "layers_common.hpp" +#include "conv2_common.hpp" +#include "cpu_kernels/fast_gemm.hpp" +#include + +// ONNX operator: DeformConv +// Spec: https://onnx.ai/onnx/operators/onnx__DeformConv.html +// Supported opsets: 19-22 (2D input only) + +namespace cv { +namespace dnn { + +class DeformConvLayerImpl CV_FINAL : public DeformConvLayer +{ +public: + int group = 1; + int offset_group = 1; + std::vector kernel_shape; // empty: take it from W + std::vector strides, dilations, pads; + FastGemmOpt gemmOpt; + + DeformConvLayerImpl(const LayerParams& params) + { + setParamsFrom(params); + gemmOpt.init(); + group = params.get("group", 1); + offset_group = params.get("offset_group", 1); + kernel_shape = params.getVector("kernel_size"); + strides = params.getVector("stride"); + dilations = params.getVector("dilation"); + pads = params.getVector("pad"); + + CV_CheckGT(group, 0, "DeformConv: group must be positive"); + CV_CheckGT(offset_group, 0, "DeformConv: offset_group must be positive"); + if (strides.empty()) strides.assign(2, 1); + if (dilations.empty()) dilations.assign(2, 1); + if (pads.empty()) pads.assign(4, 0); + CV_CheckEQ((int)strides.size(), 2, "DeformConv: only 2D input is supported"); + CV_CheckEQ((int)dilations.size(), 2, "DeformConv: only 2D input is supported"); + CV_CheckEQ((int)pads.size(), 4, "DeformConv: only 2D input is supported"); + if (!kernel_shape.empty()) + CV_CheckEQ((int)kernel_shape.size(), 2, "DeformConv: only 2D input is supported"); + } + + bool supportBackend(int backendId) CV_OVERRIDE + { + return backendId == DNN_BACKEND_OPENCV; + } + + static bool hasInput(const std::vector& inputs, size_t i) + { + return inputs.size() > i && !inputs[i].empty(); + } + + // Validates the inputs and returns the output shape. + MatShape checkShapes(const MatShape& x, const MatShape& w, const MatShape& off, + const MatShape* b, const MatShape* mask, int& kh, int& kw) const + { + CV_CheckEQ(x.dims, 4, "DeformConv: only 2D input (N x C x H x W) is supported"); + CV_CheckEQ(w.dims, 4, "DeformConv: W must be oC x C/group x kH x kW"); + CV_CheckEQ(off.dims, 4, "DeformConv: offset must be N x (offset_group*kH*kW*2) x oH x oW"); + kh = kernel_shape.empty() ? w[2] : kernel_shape[0]; + kw = kernel_shape.empty() ? w[3] : kernel_shape[1]; + CV_CheckEQ(kh, w[2], "DeformConv: kernel_shape does not match W"); + CV_CheckEQ(kw, w[3], "DeformConv: kernel_shape does not match W"); + + int C = x[1], oC = w[0]; + CV_CheckEQ(C, w[1] * group, "DeformConv: input channels must be W.shape[1] * group"); + CV_CheckEQ(oC % group, 0, "DeformConv: output channels must be divisible by group"); + CV_CheckEQ(C % offset_group, 0, "DeformConv: input channels must be divisible by offset_group"); + CV_CheckEQ(off[0], x[0], "DeformConv: offset batch size does not match X"); + CV_CheckEQ(off[1], offset_group * kh * kw * 2, "DeformConv: offset channels must be offset_group*kH*kW*2"); + + MatShape outshape = convInferShape(x, w, kernel_shape, group, strides, dilations, pads, + AUTO_PAD_NONE, false); + int oh = outshape[2], ow = outshape[3]; + CV_CheckEQ(off[2], oh, "DeformConv: offset height does not match the output height"); + CV_CheckEQ(off[3], ow, "DeformConv: offset width does not match the output width"); + + if (b) + CV_CheckEQ((int)b->total(), oC, "DeformConv: B must have oC elements"); + if (mask) + { + CV_CheckEQ(mask->dims, 4, "DeformConv: mask must be N x (offset_group*kH*kW) x oH x oW"); + CV_Assert((*mask)[0] == x[0] && (*mask)[1] == offset_group * kh * kw && + (*mask)[2] == oh && (*mask)[3] == ow && + "DeformConv: mask must be N x (offset_group*kH*kW) x oH x oW"); + } + return outshape; + } + + bool getMemoryShapes(const std::vector& inputs, + const int requiredOutputs, + std::vector& outputs, + std::vector& internals) const CV_OVERRIDE + { + CV_CheckGE((int)inputs.size(), 3, "DeformConv: X, W and offset are required"); + int kh, kw; + MatShape b, mask; + if (hasInput(inputs, 3)) b = inputs[3]; + if (hasInput(inputs, 4)) mask = inputs[4]; + MatShape outshape = checkShapes(inputs[0], inputs[1], inputs[2], + b.empty() ? nullptr : &b, mask.empty() ? nullptr : &mask, kh, kw); + outputs.assign(requiredOutputs, outshape); + // the im2col matrix of one image, C*kH*kW x oH*oW; the engine reuses it between layers + internals.clear(); + int rows = inputs[0][1] * kh * kw, L = outshape[2] * outshape[3]; + if (rows > 0 && L > 0) + internals.assign(1, MatShape({rows, L})); + return false; + } + + void getTypes(const std::vector& inputs, + const int requiredOutputs, + const int requiredInternals, + std::vector& outputs, + std::vector& internals) const CV_OVERRIDE + { + CV_CheckGE((int)inputs.size(), 3, "DeformConv: X, W and offset are required"); + CV_CheckType(inputs[0], inputs[0] == CV_32F, "DeformConv: only float32 is supported"); + CV_CheckTypeEQ(inputs[1], inputs[0], "DeformConv: W must have the same type as X"); + CV_CheckTypeEQ(inputs[2], inputs[0], "DeformConv: offset must have the same type as X"); + outputs.assign(requiredOutputs, inputs[0]); + internals.assign(requiredInternals, CV_32F); + } + + void forward(InputArrayOfArrays inputs_arr, + OutputArrayOfArrays outputs_arr, + OutputArrayOfArrays internals_arr) CV_OVERRIDE + { + std::vector inputs, outputs, internals; + inputs_arr.getMatVector(inputs); + outputs_arr.getMatVector(outputs); + internals_arr.getMatVector(internals); + CV_CheckGE((int)inputs.size(), 3, "DeformConv: X, W and offset are required"); + + Mat X = inputs[0], Wt = inputs[1], Off = inputs[2]; + Mat B = inputs.size() > 3 ? inputs[3] : Mat(); + Mat Mask = inputs.size() > 4 ? inputs[4] : Mat(); + if (!B.empty()) CV_CheckTypeEQ(B.type(), X.type(), "DeformConv: B must have the same type as X"); + if (!Mask.empty()) CV_CheckTypeEQ(Mask.type(), X.type(), "DeformConv: mask must have the same type as X"); + + int kh, kw; + MatShape bshape = B.shape(), mshape = Mask.shape(); + checkShapes(X.shape(), Wt.shape(), Off.shape(), + B.empty() ? nullptr : &bshape, Mask.empty() ? nullptr : &mshape, kh, kw); + + X = X.isContinuous() ? X : X.clone(); + Wt = Wt.isContinuous() ? Wt : Wt.clone(); + Off = Off.isContinuous() ? Off : Off.clone(); + if (!B.empty() && !B.isContinuous()) B = B.clone(); + if (!Mask.empty() && !Mask.isContinuous()) Mask = Mask.clone(); + + Mat& Y = outputs[0]; + CV_Assert(Y.isContinuous() && Y.type() == CV_32F); + + const int N = X.size[0], C = X.size[1], H = X.size[2], W = X.size[3]; + const int oC = Wt.size[0], oH = Off.size[2], oW = Off.size[3]; + const int K = kh * kw, L = oH * oW; + const int Cg = C / group, oCg = oC / group, Cog = C / offset_group; + const int sh = strides[0], sw = strides[1], dh = dilations[0], dw = dilations[1]; + const int padT = pads[0], padL = pads[1]; + + const float* xdata = X.ptr(); + const float* wdata = Wt.ptr(); + const float* offdata = Off.ptr(); + const float* bdata = B.empty() ? nullptr : B.ptr(); + const float* mdata = Mask.empty() ? nullptr : Mask.ptr(); + float* ydata = Y.ptr(); + + if (Y.total() == 0) + return; + + // im2col with deformed sampling positions: row c*K + k holds input channel c sampled at + // kernel tap k for every output position; then each group is one GEMM. + // The sampling position depends only on the offset group, so for every + // (offset group, k, i) the 4 corner indices and weights of each j are computed once + // (bilinear with zero padding, like GridSample with align_corners=1; corners outside + // the image get weight 0 and index 0, the mask is folded into the weights) and then + // reused for all channels of the offset group. + Mat cols; + if (!internals.empty() && internals[0].type() == CV_32F && internals[0].isContinuous() && + internals[0].total() >= (size_t)C * K * L) + cols = internals[0]; + else + cols.create(C * K, L, CV_32F); + float* cdata = cols.ptr(); + const int HW = H * W; + + for (int n = 0; n < N; n++) + { + const float* xn = xdata + (size_t)n * C * HW; + const float* offn = offdata + (size_t)n * offset_group * K * 2 * L; + const float* mn = mdata ? mdata + (size_t)n * offset_group * K * L : nullptr; + + parallel_for_(Range(0, offset_group * K * oH), [&](const Range& r) { + AutoBuffer idxbuf(oW * 4); + AutoBuffer wbuf(oW * 4); + int* cidx = idxbuf.data(); + float* cw = wbuf.data(); + + for (int t = r.start; t < r.end; t++) + { + int og = t / (K * oH), k = (t / oH) % K, i = t % oH; + int ki = k / kw, kj = k % kw; + const float* offY = offn + ((size_t)og * K * 2 + (size_t)k * 2) * L + (size_t)i * oW; + const float* offX = offY + L; + const float* mrow = mn ? mn + ((size_t)og * K + k) * L + (size_t)i * oW : nullptr; + float ybase = (float)(i * sh - padT + ki * dh); + + for (int j = 0; j < oW; j++) + { + float y = ybase + offY[j]; + float x = (float)(j * sw - padL + kj * dw) + offX[j]; + float m = mrow ? mrow[j] : 1.f; + int* ci = cidx + j * 4; + float* wj = cw + j * 4; + if (!(y > -1.f && y < (float)H && x > -1.f && x < (float)W)) + m = 0.f, y = x = 0.f; // also guards against NaN offsets + int y0 = cvFloor(y), x0 = cvFloor(x); + float ly = y - (float)y0, lx = x - (float)x0; + float hy = 1.f - ly, hx = 1.f - lx; + bool y0in = y0 >= 0, y1in = y0 + 1 < H, x0in = x0 >= 0, x1in = x0 + 1 < W; + ci[0] = (y0in && x0in) ? y0 * W + x0 : 0; + ci[1] = (y0in && x1in) ? y0 * W + x0 + 1 : 0; + ci[2] = (y1in && x0in) ? (y0 + 1) * W + x0 : 0; + ci[3] = (y1in && x1in) ? (y0 + 1) * W + x0 + 1 : 0; + wj[0] = (y0in && x0in) ? hy * hx * m : 0.f; + wj[1] = (y0in && x1in) ? hy * lx * m : 0.f; + wj[2] = (y1in && x0in) ? ly * hx * m : 0.f; + wj[3] = (y1in && x1in) ? ly * lx * m : 0.f; + } + + for (int c = og * Cog; c < (og + 1) * Cog; c++) + { + const float* plane = xn + (size_t)c * HW; + float* crow = cdata + ((size_t)c * K + k) * L + (size_t)i * oW; + for (int j = 0; j < oW; j++) + { + const int* ci = cidx + j * 4; + const float* wj = cw + j * 4; + crow[j] = wj[0] * plane[ci[0]] + wj[1] * plane[ci[1]] + + wj[2] * plane[ci[2]] + wj[3] * plane[ci[3]]; + } + } + } + }); + + // Y_g [oCg x L] = W_g [oCg x Cg*K] * cols_g [Cg*K x L] + const int Kg = Cg * K; + for (int g = 0; g < group; g++) + { + const float* wg = wdata + (size_t)g * oCg * Kg; + const float* cg = cdata + (size_t)g * Kg * L; + float* yg = ydata + ((size_t)n * oC + (size_t)g * oCg) * L; + fastGemm(false, false, oCg, Kg, Kg, L, 1.f, wg, Kg, 1, cg, L, 1, 0.f, yg, L, gemmOpt); + } + + if (bdata) + { + parallel_for_(Range(0, oC), [&](const Range& r) { + for (int oc = r.start; oc < r.end; oc++) + { + float* yrow = ydata + ((size_t)n * oC + oc) * L; + float bv = bdata[oc]; + for (int l = 0; l < L; l++) + yrow[l] += bv; + } + }); + } + } + } +}; + +Ptr DeformConvLayer::create(const LayerParams& params) +{ + return Ptr(new DeformConvLayerImpl(params)); +} + +}} // namespace cv::dnn diff --git a/modules/dnn/src/onnx/onnx_importer2.cpp b/modules/dnn/src/onnx/onnx_importer2.cpp index 148f2fa8b6..8baf990671 100644 --- a/modules/dnn/src/onnx/onnx_importer2.cpp +++ b/modules/dnn/src/onnx/onnx_importer2.cpp @@ -275,6 +275,7 @@ protected: void parseHammingWindow (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseCenterCropPad (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseGridSample (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); + void parseDeformConv (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseNegativeLogLikelihoodLoss(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseSoftmaxCrossEntropyLoss (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); void parseAffineGrid (LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto); @@ -2471,6 +2472,15 @@ void ONNXImporter2::parseGridSample(LayerParams& layerParams, const opencv_onnx: addLayer(layerParams, node_proto); } +void ONNXImporter2::parseDeformConv(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) +{ + int n_inputs = node_proto.input_size(); + CV_CheckGE(n_inputs, 3, "DeformConv: X, W and offset are required"); + CV_CheckLE(n_inputs, 5, "DeformConv: at most 5 inputs (X, W, offset, B, mask)"); + layerParams.type = "DeformConv"; + addLayer(layerParams, node_proto); +} + void ONNXImporter2::parseAffineGrid(LayerParams& layerParams, const opencv_onnx::NodeProto& node_proto) { layerParams.type = "AffineGrid"; @@ -3798,6 +3808,7 @@ void ONNXImporter2::buildDispatchMap_ONNX_AI() dispatch["HannWindow"] = &ONNXImporter2::parseHannWindow; dispatch["HammingWindow"] = &ONNXImporter2::parseHammingWindow; dispatch["GridSample"] = &ONNXImporter2::parseGridSample; + dispatch["DeformConv"] = &ONNXImporter2::parseDeformConv; dispatch["AffineGrid"] = &ONNXImporter2::parseAffineGrid; dispatch["RoiAlign"] = &ONNXImporter2::parseRoiAlign; dispatch["Upsample"] = &ONNXImporter2::parseUpsample; diff --git a/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp b/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp index 84c1150bdd..9ad6e3801d 100644 --- a/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp +++ b/modules/dnn/test/test_onnx_conformance_layer_filter__openvino.inl.hpp @@ -282,6 +282,10 @@ CASE(test_basic_conv_without_padding) #endif CASE(test_basic_convinteger) SKIP; +CASE(test_basic_deform_conv_with_padding) + SKIP; +CASE(test_basic_deform_conv_without_padding) + SKIP; CASE(test_batchnorm_epsilon) SKIP; CASE(test_batchnorm_epsilon_training_mode) @@ -868,6 +872,10 @@ CASE(test_cumsum_2d_int32) SKIP; CASE(test_cumsum_2d_negative_axis) // no filter +CASE(test_deform_conv_with_mask_bias) + SKIP; +CASE(test_deform_conv_with_multiple_offset_groups) + SKIP; CASE(test_depthtospace_crd_mode) // no filter if (target == DNN_TARGET_OPENCL) diff --git a/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp b/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp index 7ac0192175..70810e2dc1 100644 --- a/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp +++ b/modules/dnn/test/test_onnx_conformance_layer_parser_denylist.inl.hpp @@ -14,8 +14,6 @@ "test_ai_onnx_ml_tree_ensemble_single_tree", "test_attention_4d_diff_heads_mask4d_padded_kv", // needs the nonpad_kv_seqlen input (padded-KV variant) which is not supported yet "test_averagepool_2d_ceil_last_window_starts_on_pad", -"test_basic_deform_conv_with_padding", -"test_basic_deform_conv_without_padding", "test_batchnorm_epsilon_training_mode", // ---- same as above --- "test_batchnorm_example_training_mode", // ---- same as above --- "test_bernoulli", // Issues::Layer::Can't create layer "onnx_node_output_0!y" of type "Bernoulli" in function 'getLayerInstance' @@ -26,8 +24,6 @@ "test_bernoulli_seed_expanded", // ---- same as above --- "test_castlike_FLOAT_to_STRING", "test_castlike_STRING_to_FLOAT", // Issues::Layer::Can't create layer "onnx_node_output_0!output" of type "CastLike" in function 'getLayerInstance' -"test_deform_conv_with_mask_bias", -"test_deform_conv_with_multiple_offset_groups", "test_equal_string", "test_equal_string_broadcast", "test_identity_opt", // 23221 illegal hardware instruction diff --git a/modules/dnn/test/test_onnx_importer.cpp b/modules/dnn/test/test_onnx_importer.cpp index e2acc78169..f911c0dd55 100644 --- a/modules/dnn/test/test_onnx_importer.cpp +++ b/modules/dnn/test/test_onnx_importer.cpp @@ -341,6 +341,22 @@ TEST_P(Test_ONNX_layers, MaxUnpool_pads) testONNXModels("maxunpool_pads", npy, 0, 0, false, false, 2); } +// DeformConv cases the conformance tests don't cover: groups, offset groups, batch 2, strides, +// dilations, asymmetric pads, and a mask without a bias. +TEST_P(Test_ONNX_layers, DeformConv_groups_stride_dilation) +{ + if (backend != DNN_BACKEND_OPENCV || target != DNN_TARGET_CPU) + throw SkipTestException("Only CPU is supported"); + testONNXModels("deform_conv_groups_stride_dilation", npy, 0, 0, false, false, 4); +} + +TEST_P(Test_ONNX_layers, DeformConv_mask_no_bias) +{ + if (backend != DNN_BACKEND_OPENCV || target != DNN_TARGET_CPU) + throw SkipTestException("Only CPU is supported"); + testONNXModels("deform_conv_mask_no_bias", npy, 0, 0, false, false, 4); +} + // Opset 20 removed DFT's axis attribute; with no axis input, the axis defaults to -2. TEST_P(Test_ONNX_layers, DFT_opset20_default_axis) {