From c093fe7d3180b2ba2c24dd669bcad08b774ff0aa Mon Sep 17 00:00:00 2001 From: Prasad Ayush Kumar <129419372+Prasadayus@users.noreply.github.com> Date: Wed, 30 Sep 2026 11:34:57 +0530 Subject: [PATCH] Merge pull request #30088 from Prasadayus:unify_graph_fusion Unified DNN graph fusion behind fuseChains - #30088 Requires: https://github.com/opencv/opencv_extra/pull/1417 ### What This PR Does Follow-up to #29656, which added the backend-agnostic chain mechanism. That PR introduced it and made pointwise fusion its first consumer; this one moves the rest of the fusion onto it. - `Net::Impl::fuseBasic()` is gone. Its conv+BatchNorm, conv+activation and conv+residual branches now go through the chain mechanism. - `fuseBN` and the six other passes now run from inside `fuseChains()`, in their existing order. - `graph_fusion_basic.cpp` keeps `fuseBN()` and `fuseInstanceNormAffine()`. - New `FusionOps::foldInputScale` folds a scale sitting before a conv directly into its weights, across the dense, depthwise, grouped and MLAS-prepacked layouts. ### Results Measured on Intel Core i9-11900K | Model | 5.x | this PR | speedup | |-----------------------------|-----------|-----------|---------| | inception_v2 | 15.04 ms | 11.80 ms | 1.27 | | efficientnet-lite4 | 14.83 ms | 12.28 ms | 1.21 | | pose_estimation_mediapipe | 5.66 ms | 5.25 ms | 1.08 | | siglip_base_patch16_224 | 143.04 ms | 135.27 ms | 1.06 | | densenet121 | 25.99 ms | 24.76 ms | 1.05 | ### Pull Request Readiness Checklist See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request - [x] I agree to contribute to the project under Apache 2 License. - [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV - [x] The PR is proposed to the proper branch - [x] There is a reference to the original bug report and related work - [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable Patch to opencv_extra has the same branch name. - [x] The feature is well documented and sample code can be built with the project CMake --- .../dnn/include/opencv2/dnn/all_layers.hpp | 3 - modules/dnn/src/adjacency_graph.hpp | 99 +++- modules/dnn/src/graph_fusion_basic.cpp | 359 +++++---------- modules/dnn/src/graph_fusion_chain.cpp | 227 ++++++++-- modules/dnn/src/layers/batch_norm2_layer.cpp | 37 ++ modules/dnn/src/layers/conv2_common.cpp | 24 +- modules/dnn/src/layers/conv2_common.hpp | 38 ++ modules/dnn/src/layers/conv2_layer.cpp | 425 ++++++++++++------ .../src/layers/cpu_kernels/fusion_apply.hpp | 5 + modules/dnn/src/layers/elementwise_layers.cpp | 142 +++++- .../dnn/src/layers/nary_eltwise_layers.cpp | 8 + modules/dnn/src/net_impl.hpp | 4 +- modules/dnn/src/net_impl2.cpp | 8 - modules/dnn/test/test_fusion.cpp | 179 ++++++++ 14 files changed, 1086 insertions(+), 472 deletions(-) diff --git a/modules/dnn/include/opencv2/dnn/all_layers.hpp b/modules/dnn/include/opencv2/dnn/all_layers.hpp index 88e94bd4c6..25483466e0 100644 --- a/modules/dnn/include/opencv2/dnn/all_layers.hpp +++ b/modules/dnn/include/opencv2/dnn/all_layers.hpp @@ -385,9 +385,6 @@ CV__DNN_INLINE_NS_BEGIN virtual void setWeights(InputArray weights, InputArray bias, int C0, int accuracy) = 0; virtual bool fuseAddBias(InputArray bias) = 0; - virtual bool fuseBatchNorm(const Ptr& bn) = 0; - virtual bool fuseActivation(const Ptr& activ) = 0; - virtual bool fuseAddResidual(Arg residual) = 0; std::vector strides, dilations, pads; int ngroups; diff --git a/modules/dnn/src/adjacency_graph.hpp b/modules/dnn/src/adjacency_graph.hpp index c09e4ae580..c0bb5de8de 100644 --- a/modules/dnn/src/adjacency_graph.hpp +++ b/modules/dnn/src/adjacency_graph.hpp @@ -31,6 +31,7 @@ enum class FusionEltwiseOp INPUT, CONST, PER_CHANNEL_CONST, + TENSOR, ADD, SUB, MUL, @@ -52,6 +53,7 @@ inline int arity(FusionEltwiseOp op) case FusionEltwiseOp::INPUT: case FusionEltwiseOp::CONST: case FusionEltwiseOp::PER_CHANNEL_CONST: + case FusionEltwiseOp::TENSOR: return 0; case FusionEltwiseOp::ADD: case FusionEltwiseOp::SUB: @@ -77,10 +79,12 @@ inline unsigned bits(float f) { Cv32suf s; s.f = f; return s.u; } /** @brief One constant operand: a scalar, or a per-channel buffer. */ struct FusionConst { - float value = 0.f; //!< the scalar, meaningful only while bufferId < 0 + float value = 0.f; //!< the scalar, meaningful only while bufferId and tensorId are < 0 int bufferId = -1; //!< >=0 selects a per-channel buffer, indexes constBufs + int tensorId = -1; //!< >=0 selects another layer's live output, indexes tensorArgs bool isBuffer() const { return bufferId >= 0; } + bool isTensor() const { return tensorId >= 0; } }; /** @brief The constant operands a layer has alongside the value flowing into it, kept in @@ -167,6 +171,14 @@ struct LayerMath 0.f, 0.f, bufferId); } + //! For a live tensor, at the slot the pass assigned it in the chain's tensorArgs. + int tensorOperand(int tensorId) + { + CV_Assert(tensorId >= 0); + return appendNode(FusionEltwiseOp::TENSOR, INPUT_VALUE, INPUT_VALUE, + 0.f, 0.f, tensorId); + } + int unary(FusionEltwiseOp op, int operand) { CV_Assert(fusion::detail::arity(op) == 1); @@ -199,17 +211,44 @@ private: namespace fusion { namespace detail { -inline void sigmoid(LayerMath& r) +inline int sigmoid(LayerMath& r) { const int one = r.constant(1.f); const int minusOne = r.constant(-1.f); const int negated = r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, minusOne); const int exponent = r.unary(FusionEltwiseOp::EXP, negated); const int denom = r.binary(FusionEltwiseOp::ADD, one, exponent); - r.unary(FusionEltwiseOp::RECIP, denom); + return r.unary(FusionEltwiseOp::RECIP, denom); } -inline void gelu(LayerMath& r) +inline int abs(LayerMath& r, int operand) +{ + const int minusOne = r.constant(-1.f); + const int negated = r.binary(FusionEltwiseOp::MUL, operand, minusOne); + return r.binary(FusionEltwiseOp::MAX, operand, negated); +} + +//! max(x,0) + alpha*(exp(min(x,0)*xScale) - 1). The arms never overlap because +//! exp(0) - 1 is exactly 0, so the one that does not apply contributes nothing. +inline int expLinearUnit(LayerMath& r, float alpha, float xScale) +{ + const int zero = r.constant(0.f); + const int one = r.constant(1.f); + const int pos = r.binary(FusionEltwiseOp::MAX, LayerMath::INPUT_VALUE, zero); + const int clipped = r.binary(FusionEltwiseOp::MIN, LayerMath::INPUT_VALUE, zero); + int neg = clipped; + if (xScale != 1.f) { + const int s = r.constant(xScale); + neg = r.binary(FusionEltwiseOp::MUL, clipped, s); + } + const int expNeg = r.unary(FusionEltwiseOp::EXP, neg); + const int decayed = r.binary(FusionEltwiseOp::SUB, expNeg, one); + const int a = r.constant(alpha); + const int scaled = r.binary(FusionEltwiseOp::MUL, a, decayed); + return r.binary(FusionEltwiseOp::ADD, pos, scaled); +} + +inline int gelu(LayerMath& r) { const int half = r.constant(0.5f); const int one = r.constant(1.f); @@ -218,7 +257,7 @@ inline void gelu(LayerMath& r) const int erfTerm = r.unary(FusionEltwiseOp::ERF, scaled); const int gate = r.binary(FusionEltwiseOp::ADD, one, erfTerm); const int halfX = r.binary(FusionEltwiseOp::MUL, half, LayerMath::INPUT_VALUE); - r.binary(FusionEltwiseOp::MUL, halfX, gate); + return r.binary(FusionEltwiseOp::MUL, halfX, gate); } }} // namespace fusion::detail @@ -269,6 +308,11 @@ public: std::vector constBufs; + //! Live tensor operands, indexed by each TENSOR node's constBufferId; extract() remaps them. + std::vector tensorArgs; + //! Parallel to constBufs: the layer declared it per-channel, so do not infer the axis. + std::vector constBufPerChannel; + //! Set when this whole expression is one layer that already has a kernel. FusionKernel kernel; @@ -303,7 +347,8 @@ public: if (op != FusionEltwiseOp::CONST && op != FusionEltwiseOp::CLAMP) scalar = 0.f; if (op != FusionEltwiseOp::CLAMP) scalar2 = 0.f; - if (op != FusionEltwiseOp::PER_CHANNEL_CONST) constBufferId = -1; + if (op != FusionEltwiseOp::PER_CHANNEL_CONST && op != FusionEltwiseOp::TENSOR) + constBufferId = -1; FusionNode cand; cand.op = op; @@ -394,6 +439,10 @@ inline float evalElement(const AdjacencyGraph& g, float x, case FusionEltwiseOp::CLAMP: v[i] = a < n.scalar ? n.scalar : (a > n.scalar2 ? n.scalar2 : a); break; + case FusionEltwiseOp::TENSOR: + // Only a sink that opted in is offered one, and it reads the nodes itself. + CV_Error(Error::StsNotImplemented, + "DNN/fusion: TENSOR operand reached the generic interpreter"); } } return v[out]; @@ -422,7 +471,9 @@ inline int markLive(const AdjacencyGraph& g, int root, std::vector& live) } // namespace detail inline Ptr extract(const AdjacencyGraph& arena, int root, - const std::vector& constBufs) + const std::vector& constBufs, + const std::vector& perChannel = std::vector(), + const std::vector& tensorArgs = std::vector()) { const std::vector& src = arena.nodes(); if (root < 0 || root >= (int)src.size()) @@ -435,6 +486,9 @@ inline Ptr extract(const AdjacencyGraph& arena, int root, return Ptr(); std::vector remap(live.size(), -1); + // tensorId -> slot in outTensorArgs, so a shorter offer only carries the tensors it reads. + std::vector tensorRemap(tensorArgs.size(), -1); + std::vector outTensorArgs; AdjacencyGraphBuilder out; remap[0] = out.internNode(FusionEltwiseOp::INPUT, {}); @@ -462,16 +516,28 @@ inline Ptr extract(const AdjacencyGraph& arena, int root, if (n.op == FusionEltwiseOp::PER_CHANNEL_CONST && (n.constBufferId < 0 || n.constBufferId >= (int)constBufs.size())) return Ptr(); + int constBufferId = n.constBufferId; + if (n.op == FusionEltwiseOp::TENSOR) { + if (n.constBufferId < 0 || n.constBufferId >= (int)tensorArgs.size()) + return Ptr(); + if (tensorRemap[n.constBufferId] < 0) { + tensorRemap[n.constBufferId] = (int)outTensorArgs.size(); + outTensorArgs.push_back(tensorArgs[n.constBufferId]); + } + constBufferId = tensorRemap[n.constBufferId]; + } std::vector ins(n.inputs.size()); for (size_t k = 0; k < ins.size(); k++) ins[k] = remap[n.inputs[k]]; - remap[i] = out.internNode(n.op, ins, n.scalar, n.scalar2, n.constBufferId); + remap[i] = out.internNode(n.op, ins, n.scalar, n.scalar2, constBufferId); } if (remap[root] != (int)out.size() - 1) return Ptr(); Ptr g = out.finish(remap[root]); g->constBufs = constBufs; + g->constBufPerChannel = perChannel; + g->tensorArgs = outTensorArgs; return g; } @@ -505,6 +571,23 @@ struct FusionOps * responsible for computing it. A null slot means it never takes one. */ bool (*absorb)(Layer* self, const Ptr& expr); + + //! Opt-in: lets a chain grow through a live-tensor (TENSOR) side operand. The pass wires + //! the accepted expression's tensorArgs on as extra layer inputs, in order. + bool acceptsTensorOperands = false; + + //! Folds a per-input-channel scale and shift into the layer's own weights, so a pass can + //! do it without knowing how they are packed. A null slot means the layer never does. + bool (*foldInputScale)(Layer* self, const Mat& scale, const Mat& shift) = nullptr; + + /** @brief Names per-channel data an earlier pass folded into the layer's own members, + * which therefore has no Arg for the pass to read. + * + * The pass slots these before calling unfold and hands their ids over in @c side, the + * same way it hands over the ones it read from the layer's inputs. @p out is filled in + * the order unfold expects to read it back. A null slot means the layer owns none. + */ + bool (*ownedBuffers)(const Layer* self, std::vector& out) = nullptr; }; /** @brief Binds @p ops to one concrete layer class. Last registration for a type wins. */ diff --git a/modules/dnn/src/graph_fusion_basic.cpp b/modules/dnn/src/graph_fusion_basic.cpp index ef95b05d76..903133fbd8 100644 --- a/modules/dnn/src/graph_fusion_basic.cpp +++ b/modules/dnn/src/graph_fusion_basic.cpp @@ -4,6 +4,7 @@ #include "precomp.hpp" #include "net_impl.hpp" +#include "adjacency_graph.hpp" namespace cv { namespace dnn { CV__DNN_INLINE_NS_BEGIN @@ -14,9 +15,11 @@ using std::string; typedef std::pair int_pair; typedef std::pair int_arg_pair; -struct ModelFusionBasic +//! Reshape+InstanceNorm(1,0)+Reshape+Mul+Add collapsed into one layer. It matches +//! backward from the Add and can swap the survivor's type, so it is not a chain. +struct InstanceNormAffineFusion { - ModelFusionBasic(Net::Impl* netimpl_) : netimpl(netimpl_) {} + InstanceNormAffineFusion(Net::Impl* netimpl_) : netimpl(netimpl_) {} void fuse() { @@ -43,7 +46,6 @@ struct ModelFusionBasic size_t i, nargs = netimpl->args.size(), nops = prog.size(); std::vector producer_of(nargs, -1); std::vector > newprog; - std::vector fused_inputs; for (i = 0; i < nops; i++) { const Ptr& layer = prog[i]; @@ -60,170 +62,99 @@ struct ModelFusionBasic const std::vector& outputs = layer->outputs; size_t ninputs = inputs.size(); removed_args.clear(); - fused_inputs.clear(); // leave it empty in the merge patterns below to re-use original fused node inputs as-is. - for(;;) { - BatchNorm2Layer* bn = dynamic_cast(layer_ptr); - ActivationLayer* activ = dynamic_cast(layer_ptr); - NaryEltwiseLayer* elemwise = dynamic_cast(layer_ptr); + NaryEltwiseLayer* elemwise = dynamic_cast(layer_ptr); - // merge convolution and batch norm - if (bn && ninputs == 1 && - usecounts.at(inputs[0].idx) == 1) { - Arg bn_inp = inputs[0]; - int conv_layer_idx = producer_of.at(bn_inp.idx); - Conv2Layer* conv = getLayer(newprog, conv_layer_idx); - if (conv) { - bool ok = conv->fuseBatchNorm(layer.dynamicCast()); - if (ok) { - fused_layer_idx = conv_layer_idx; - removed_args.push_back(bn_inp); - break; - } + // fuse Reshape + InstanceNorm(scale=ones,bias=zeros) + Reshape + Mul + Add + if (elemwise && elemwise->op == NaryEltwiseLayer::OPERATION::ADD && + ninputs == 2) { + int mul_input_idx = -1; + Arg add_bias_arg; + for (int k = 0; k < 2; k++) { + int pidx = producer_of.at(inputs[k].idx); + NaryEltwiseLayer* mul = getLayer(newprog, pidx); + if (mul && mul->op == NaryEltwiseLayer::OPERATION::PROD) { + mul_input_idx = k; + add_bias_arg = inputs[1 - k]; + break; } } - - // merge residual 'add' into 'conv' node - if (elemwise && (elemwise->op == NaryEltwiseLayer::OPERATION::ADD || - elemwise->op == NaryEltwiseLayer::OPERATION::SUM) && - ninputs == 2) { - - int op0 = producer_of.at(inputs[0].idx); - int op1 = producer_of.at(inputs[1].idx); - - if (op0 >= 0 && op1 >= 0) { - int conv_layer_idx; - Arg residual, conv_out; - - if (op0 > op1) { // choose the latter op to ensure that the other component is already computed - conv_layer_idx = op0; - conv_out = inputs[0]; - residual = inputs[1]; - } else { - conv_layer_idx = op1; - conv_out = inputs[1]; - residual = inputs[0]; - } - - Conv2Layer* conv = getLayer(newprog, conv_layer_idx); - if (conv && usecounts[conv_out.idx] == 1 && - conv->fuseAddResidual(residual)) { - fused_layer_idx = conv_layer_idx; - removed_args.push_back(conv_out); - break; - } - } - } - - // merge convolution and activation - if (activ && ninputs == 1 && - usecounts.at(inputs[0].idx) == 1) { - Arg activ_inp = inputs[0]; - int conv_layer_idx = producer_of.at(activ_inp.idx); - Conv2Layer* conv = getLayer(newprog, conv_layer_idx); - if (conv) { - bool ok = conv->fuseActivation(layer.dynamicCast()); - if (ok) { - fused_layer_idx = conv_layer_idx; - removed_args.push_back(activ_inp); - break; - } - } - } - - // fuse Reshape + InstanceNorm(scale=ones,bias=zeros) + Reshape + Mul + Add - if (elemwise && elemwise->op == NaryEltwiseLayer::OPERATION::ADD && - ninputs == 2) { - int mul_input_idx = -1; - Arg add_bias_arg; - for (int k = 0; k < 2; k++) { - int pidx = producer_of.at(inputs[k].idx); - NaryEltwiseLayer* mul = getLayer(newprog, pidx); - if (mul && mul->op == NaryEltwiseLayer::OPERATION::PROD) { - mul_input_idx = k; - add_bias_arg = inputs[1 - k]; - break; - } - } - if (mul_input_idx >= 0 && netimpl->isConstArg(add_bias_arg)) { - Arg mul_out = inputs[mul_input_idx]; - int mul_idx = producer_of.at(mul_out.idx); - NaryEltwiseLayer* mul = getLayer(newprog, mul_idx); - if (mul && mul->inputs.size() == 2 && - usecounts.at(mul_out.idx) == 1) { - int reshape2_input_idx = -1; - Arg mul_scale_arg; - for (int k = 0; k < 2; k++) { - int pidx = producer_of.at(mul->inputs[k].idx); - if (getLayer(newprog, pidx)) { - reshape2_input_idx = k; - mul_scale_arg = mul->inputs[1 - k]; - break; - } + if (mul_input_idx >= 0 && netimpl->isConstArg(add_bias_arg)) { + Arg mul_out = inputs[mul_input_idx]; + int mul_idx = producer_of.at(mul_out.idx); + NaryEltwiseLayer* mul = getLayer(newprog, mul_idx); + if (mul && mul->inputs.size() == 2 && + usecounts.at(mul_out.idx) == 1) { + int reshape2_input_idx = -1; + Arg mul_scale_arg; + for (int k = 0; k < 2; k++) { + int pidx = producer_of.at(mul->inputs[k].idx); + if (getLayer(newprog, pidx)) { + reshape2_input_idx = k; + mul_scale_arg = mul->inputs[1 - k]; + break; } - if (reshape2_input_idx >= 0 && netimpl->isConstArg(mul_scale_arg)) { - Arg reshape2_out = mul->inputs[reshape2_input_idx]; - int reshape2_idx = producer_of.at(reshape2_out.idx); - Reshape2Layer* reshape2_lyr = getLayer(newprog, reshape2_idx); - if (reshape2_lyr && reshape2_lyr->inputs.size() >= 1 && - usecounts.at(reshape2_out.idx) == 1) { - Arg reshape2_inp = reshape2_lyr->inputs[0]; - int instnorm_idx = producer_of.at(reshape2_inp.idx); - InstanceNormLayer* instnorm = getLayer(newprog, instnorm_idx); - if (instnorm && instnorm->inputs.size() == 3 && - usecounts.at(reshape2_inp.idx) == 1) { - Arg instnorm_inp = instnorm->inputs[0]; - int reshape1_idx = producer_of.at(instnorm_inp.idx); - Reshape2Layer* reshape1_lyr = getLayer(newprog, reshape1_idx); - if (reshape1_lyr && reshape1_lyr->outputs.size() == 1 && - usecounts.at(instnorm_inp.idx) == 1) { - Mat in_scale = netimpl->isConstArg(instnorm->inputs[1]) ? - netimpl->argTensor(instnorm->inputs[1]) : Mat(); - Mat in_bias = netimpl->isConstArg(instnorm->inputs[2]) ? - netimpl->argTensor(instnorm->inputs[2]) : Mat(); - bool valid = !in_scale.empty() && !in_bias.empty() && - in_scale.type() == CV_32F && in_bias.type() == CV_32F; - if (valid) { - const float* sp = in_scale.ptr(); - const float* bp = in_bias.ptr(); - bool all_ones = true, all_zeros = true; - for (size_t k = 0; k < in_scale.total() && all_ones; k++) - all_ones = (std::abs(sp[k] - 1.f) < 1e-6f); - for (size_t k = 0; k < in_bias.total() && all_zeros; k++) - all_zeros = (std::abs(bp[k]) < 1e-6f); - if (all_ones && all_zeros) { - Arg orig_inp = reshape1_lyr->inputs[0]; - Mat mul_scale_mat = netimpl->argTensor(mul_scale_arg); - if (in_scale.total() == mul_scale_mat.total()) { - // Channel dim preserved — fuse into InstanceNorm - instnorm->inputs[0] = orig_inp; - instnorm->inputs[1] = mul_scale_arg; - instnorm->inputs[2] = add_bias_arg; - } else { - // Channel dim changed (e.g. [1,C,H,W]->[1,1,C*H*W]): - // original is global norm + per-channel affine. - // Replace with GroupNorm(num_groups=reshaped_C). - int num_groups = (int)in_scale.total(); - LayerParams gnparams; - gnparams.name = instnorm->name; - gnparams.type = "GroupNormalization"; - gnparams.set("epsilon", instnorm->epsilon); - gnparams.set("num_groups", num_groups); - Ptr gnlayer = GroupNormLayer::create(gnparams); - gnlayer->netimpl = netimpl; - gnlayer->inputs = {orig_inp, mul_scale_arg, add_bias_arg}; - newprog[instnorm_idx] = gnlayer; - } - fused_layer_idx = instnorm_idx; - removed_args.push_back(instnorm_inp); - removed_args.push_back(reshape2_inp); - removed_args.push_back(reshape2_out); - removed_args.push_back(mul_out); - newprog[reshape1_idx] = Ptr(); - newprog[reshape2_idx] = Ptr(); - newprog[mul_idx] = Ptr(); - break; + } + if (reshape2_input_idx >= 0 && netimpl->isConstArg(mul_scale_arg)) { + Arg reshape2_out = mul->inputs[reshape2_input_idx]; + int reshape2_idx = producer_of.at(reshape2_out.idx); + Reshape2Layer* reshape2_lyr = getLayer(newprog, reshape2_idx); + if (reshape2_lyr && reshape2_lyr->inputs.size() >= 1 && + usecounts.at(reshape2_out.idx) == 1) { + Arg reshape2_inp = reshape2_lyr->inputs[0]; + int instnorm_idx = producer_of.at(reshape2_inp.idx); + InstanceNormLayer* instnorm = getLayer(newprog, instnorm_idx); + if (instnorm && instnorm->inputs.size() == 3 && + usecounts.at(reshape2_inp.idx) == 1) { + Arg instnorm_inp = instnorm->inputs[0]; + int reshape1_idx = producer_of.at(instnorm_inp.idx); + Reshape2Layer* reshape1_lyr = getLayer(newprog, reshape1_idx); + if (reshape1_lyr && reshape1_lyr->outputs.size() == 1 && + usecounts.at(instnorm_inp.idx) == 1) { + Mat in_scale = netimpl->isConstArg(instnorm->inputs[1]) ? + netimpl->argTensor(instnorm->inputs[1]) : Mat(); + Mat in_bias = netimpl->isConstArg(instnorm->inputs[2]) ? + netimpl->argTensor(instnorm->inputs[2]) : Mat(); + bool valid = !in_scale.empty() && !in_bias.empty() && + in_scale.type() == CV_32F && in_bias.type() == CV_32F; + if (valid) { + const float* sp = in_scale.ptr(); + const float* bp = in_bias.ptr(); + bool all_ones = true, all_zeros = true; + for (size_t k = 0; k < in_scale.total() && all_ones; k++) + all_ones = (std::abs(sp[k] - 1.f) < 1e-6f); + for (size_t k = 0; k < in_bias.total() && all_zeros; k++) + all_zeros = (std::abs(bp[k]) < 1e-6f); + if (all_ones && all_zeros) { + Arg orig_inp = reshape1_lyr->inputs[0]; + Mat mul_scale_mat = netimpl->argTensor(mul_scale_arg); + if (in_scale.total() == mul_scale_mat.total()) { + // Channel dim preserved — fuse into InstanceNorm + instnorm->inputs[0] = orig_inp; + instnorm->inputs[1] = mul_scale_arg; + instnorm->inputs[2] = add_bias_arg; + } else { + // [1,C,H,W]->[1,1,C*H*W] folds C into spatial, + // so this is global norm + per-channel affine. + int num_groups = (int)in_scale.total(); + LayerParams gnparams; + gnparams.name = instnorm->name; + gnparams.type = "GroupNormalization"; + gnparams.set("epsilon", instnorm->epsilon); + gnparams.set("num_groups", num_groups); + Ptr gnlayer = GroupNormLayer::create(gnparams); + gnlayer->netimpl = netimpl; + gnlayer->inputs = {orig_inp, mul_scale_arg, add_bias_arg}; + newprog[instnorm_idx] = gnlayer; } + fused_layer_idx = instnorm_idx; + removed_args.push_back(instnorm_inp); + removed_args.push_back(reshape2_inp); + removed_args.push_back(reshape2_out); + removed_args.push_back(mul_out); + newprog[reshape1_idx] = Ptr(); + newprog[reshape2_idx] = Ptr(); + newprog[mul_idx] = Ptr(); } } } @@ -232,7 +163,6 @@ struct ModelFusionBasic } } } - break; } if (fused_layer_idx >= 0) { @@ -274,10 +204,10 @@ struct ModelFusionBasic vector usecounts; }; -void Net::Impl::fuseBasic() +void Net::Impl::fuseInstanceNormAffine() { - ModelFusionBasic basicFusion(this); - basicFusion.fuse(); + InstanceNormAffineFusion fusion(this); + fusion.fuse(); } // fold BN scale/bias into the weights of the immediately following Conv2 (pre-constArgs only) @@ -349,103 +279,22 @@ struct FuseBNPass } } - // fold BN scale/bias into Conv2 weight and bias tensors (raw NCHW fp32 only) + // Ask the conv to take the BatchNorm's scale and shift into its own weights. It owns + // the layout, so this works after constArgs() has packed them. bool fuseForward(Conv2Layer* conv, BatchNorm2Layer* bn) { - // skip padded convolutions: border taps get incorrect bias from folded BN - for (int p : conv->pads) - if (p > 0) return false; - - if (conv->inputs.size() < 2 || !netimpl->isConstArg(conv->inputs[1])) + if (bn->inputs.size() != 1) + return false; // constArgs() freezes a const-parameter BN down to one input + Mat scale, shift; + bn->getScaleBias(scale, shift); + if (scale.empty() || shift.empty()) return false; - - Mat& Wref = netimpl->argTensor(conv->inputs[1]); - if (Wref.empty() || Wref.type() != CV_32F || Wref.dims != 4) - return false; - - int OC = Wref.size[0]; - int IC_pg = Wref.size[1]; // input channels per group - int KH = Wref.size[2]; - int KW = Wref.size[3]; - int ngroups = conv->ngroups; - if (ngroups <= 0 || OC % ngroups != 0) - return false; - int OC_pg = OC / ngroups; - - // resolve BN effective scale and bias; validate all params are const - Mat bn_scale, bn_bias_vec; - size_t bn_nin = bn->inputs.size(); - if (bn_nin == 5) { - for (int k = 1; k <= 4; k++) - if (!netimpl->isConstArg(bn->inputs[k])) return false; - BatchNorm2Layer::getScaleBias( - netimpl->argTensor(bn->inputs[1]), - netimpl->argTensor(bn->inputs[2]), - netimpl->argTensor(bn->inputs[3]), - netimpl->argTensor(bn->inputs[4]), - bn->epsilon, bn_scale, bn_bias_vec); - } else if (bn_nin == 1) { - bn->getScaleBias(bn_scale, bn_bias_vec); - } else { - return false; - } - - bn_scale.convertTo(bn_scale, CV_32F); - bn_bias_vec.convertTo(bn_bias_vec, CV_32F); - - if ((int)bn_scale.total() != IC_pg * ngroups) - return false; - - const float* bn_s = bn_scale.ptr(); - const float* bn_b = bn_bias_vec.ptr(); - - // reshape to 2D [OC, IC_pg*KH*KW]; shares buffer with Wref - Mat W2d = Wref.reshape(1, OC); - - // scale weights in-place; accumulate per-output-channel bias correction - bias_adj.assign(OC, 0.f); - for (int g = 0; g < ngroups; g++) { - int ic_off = g * IC_pg; - for (int oc = g * OC_pg, oc_end = oc + OC_pg; oc < oc_end; oc++) { - float* wrow = W2d.ptr(oc); - for (int ic = 0; ic < IC_pg; ic++) { - float s = bn_s[ic_off + ic]; - float b = bn_b[ic_off + ic]; - float* wic = wrow + ic * KH * KW; - float sw = 0.f; - for (int k = 0; k < KH * KW; k++) { - sw += wic[k]; - wic[k] *= s; - } - bias_adj[oc] += b * sw; - } - } - } - - // apply bias correction into existing bias tensor or create a new one - size_t conv_nin = conv->inputs.size(); - if (conv_nin >= 3 && netimpl->isConstArg(conv->inputs[2])) { - Mat& Bref = netimpl->argTensor(conv->inputs[2]); - if (Bref.type() != CV_32F || (int)Bref.total() != OC) - return false; - float* bp = Bref.ptr(); - for (int oc = 0; oc < OC; oc++) - bp[oc] += bias_adj[oc]; - } else { - Mat newB(1, OC, CV_32F); - std::memcpy(newB.ptr(), bias_adj.data(), OC * sizeof(float)); - Arg ba = netimpl->newConstArg( - "__fused_bn_bias_w" + std::to_string(conv->inputs[1].idx), newB); - if (conv_nin == 2) conv->inputs.push_back(ba); - else conv->inputs[2] = ba; - } - - return true; + const FusionOps* ops = fusionOpsFor(conv); + return ops && ops->foldInputScale && ops->foldInputScale(conv, scale, shift); } Net::Impl* netimpl; std::vector usecounts; - std::vector bias_adj; }; void Net::Impl::fuseBN() diff --git a/modules/dnn/src/graph_fusion_chain.cpp b/modules/dnn/src/graph_fusion_chain.cpp index 3a1a76a8fd..b78c5e2556 100644 --- a/modules/dnn/src/graph_fusion_chain.cpp +++ b/modules/dnn/src/graph_fusion_chain.cpp @@ -28,6 +28,18 @@ void firstConsumerOf(const vector >& prog, int nargs, } } +void producerOf(const vector >& prog, int nargs, vector& producer) +{ + producer.assign((size_t)nargs, -1); + for (size_t j = 0; j < prog.size(); j++) { + if (!prog[j]) continue; + for (Arg out : prog[j]->outputs) { + if (out.idx > 0 && out.idx < nargs) + producer[out.idx] = (int)j; + } + } +} + class ChainFuser { public: @@ -56,14 +68,24 @@ public: } private: + //! A per-channel constant the chain carries. Its slot id is the index here, and the + //! arena interns that id, so slots are only ever appended or trimmed off the end. + struct ConstSlot + { + Mat buf; + Arg arg; //!< default when the layer owns the data + uchar perChannel = 0; //!< 1 varies along the channel axis, 0 along the last + }; + struct ChainCandidate { vector layerIdx; - vector constArgs; vector rootAfterStep; - vector constBufs; + vector constSlots; //! First step's kernel; a chain that lands at one step runs it instead of the DAG. FusionKernel singleStepKernel; + //! Live tensors the steps read, in the order their slots were handed out. + vector tensorArgs; }; const vector >& prog() const { return graph_->prog(); } @@ -89,18 +111,70 @@ private: return true; } - //! The slot @p a occupies in the chain's per-channel buffer list, adding it if new. - static int bufferSlotFor(Arg a, ChainCandidate& c) + //! Releases the slots a refused step claimed, so the next step's ids start where it did. + static void dropSlotsAfter(ChainCandidate& c, size_t keepBufs, size_t keepTensors) { - for (size_t k = 0; k < c.constArgs.size(); k++) { - if (c.constArgs[k].idx == a.idx) - return (int)k; - } - c.constArgs.push_back(a); - return (int)c.constArgs.size() - 1; + c.constSlots.resize(keepBufs); + c.tensorArgs.resize(keepTensors); } - bool readConstOperand(const Ptr& L, Arg cur, ChainCandidate& c, ConstOperand& out) const + //! The slot @p a occupies in the chain's live-tensor list, adding it if new. + static int tensorSlotFor(Arg a, ChainCandidate& c) + { + for (size_t k = 0; k < c.tensorArgs.size(); k++) { + if (c.tensorArgs[k].idx == a.idx) + return (int)k; + } + c.tensorArgs.push_back(a); + return (int)c.tensorArgs.size() - 1; + } + + //! Producer must precede @p anchor and the arg must not be a graph output. No type check: + //! an intermediate's ArgData is filled only at run time, so a gate here rejects them all. + bool isFusableTensorArg(Arg a, size_t anchor) const + { + if (a.idx <= 0 || a.idx >= (int)producerOf_.size()) + return false; + const int prod = producerOf_[a.idx]; + if (prod < 0 || prod >= (int)anchor) + return false; + return externalArgs_.find(a.idx) == externalArgs_.end(); + } + + //! The slot @p a occupies in the chain's per-channel buffer list, adding it if new. + int bufferSlotFor(Arg a, ChainCandidate& c) const + { + // Owned buffers park Arg() in the table, so a real input must never match one. + CV_DbgAssert(a.idx != 0); + for (size_t k = 0; k < c.constSlots.size(); k++) { + if (c.constSlots[k].arg.idx == a.idx) + return (int)k; + } + c.constSlots.push_back({net_.argTensor(a), a, 0}); + return (int)c.constSlots.size() - 1; + } + + //! Per-channel data the layer folded into its members has no Arg, so it is slotted here + //! and its ids join the ones readConstOperand() took from the layer's inputs. + static bool addOwnedBuffers(const FusionOps* ops, Layer* l, ChainCandidate& c, + ConstOperand& out) + { + if (!ops->ownedBuffers) + return true; + std::vector owned; + if (!ops->ownedBuffers(l, owned)) + return false; + if (out.count + (int)owned.size() > ConstOperand::MAX_CONSTS) + return false; + for (const Mat& buf : owned) { + c.constSlots.push_back({buf, Arg(), 1}); + out.consts[out.count++].bufferId = (int)c.constSlots.size() - 1; + } + return true; + } + + bool readConstOperand(const Ptr& L, Arg cur, ChainCandidate& c, + ConstOperand& out, size_t anchor, bool acceptsTensors) const { vector sideInputs; for (Arg in : L->inputs) { @@ -118,12 +192,16 @@ private: for (size_t i = 0; i < sideInputs.size(); i++) { bool isScalar = false; float scalarVal = 0.f; - if (!isFusableConstArg(sideInputs[i], isScalar, scalarVal)) + if (isFusableConstArg(sideInputs[i], isScalar, scalarVal)) { + if (isScalar) + out.consts[i].value = scalarVal; + else + out.consts[i].bufferId = bufferSlotFor(sideInputs[i], c); + continue; + } + if (!acceptsTensors || !isFusableTensorArg(sideInputs[i], anchor)) return false; - if (isScalar) - out.consts[i].value = scalarVal; - else - out.consts[i].bufferId = bufferSlotFor(sideInputs[i], c); + out.consts[i].tensorId = tensorSlotFor(sideInputs[i], c); } out.count = (int)sideInputs.size(); return true; @@ -134,18 +212,28 @@ private: const FusionOps* ops = fusionOpsFor(l); if (!ops || !ops->unfold) return false; - // We don't know yet how many constants this layer will get, so try each count. + // The operand count and kind are not known yet, so try every combination. for (int n = 0; n <= ConstOperand::MAX_CONSTS; n++) { - LayerMath r; - ConstOperand probe; - probe.count = n; - if (ops->unfold(l, r, probe)) - return true; + for (int kind = 0; kind < 3; kind++) { + if (kind > 0 && n == 0) + continue; // nothing to mark, so it repeats the probe above + LayerMath r; + ConstOperand probe; + probe.count = n; + for (int i = 0; i < n; i++) { + if (kind == 1) + probe.consts[i].bufferId = i; + else if (kind == 2) + probe.consts[i].tensorId = i; + } + if (ops->unfold(l, r, probe)) + return true; + } } return false; } - void growChain(size_t anchor, ChainCandidate& c) + void growChain(size_t anchor, bool acceptsTensors, ChainCandidate& c) { CV_Assert(!arenaPtr_); @@ -176,17 +264,33 @@ private: if (!ops || !ops->unfold) break; - const size_t savedSlots = c.constArgs.size(); + const size_t savedBufs = c.constSlots.size(); + const size_t savedTensors = c.tensorArgs.size(); ConstOperand side; LayerMath r; - if (!readConstOperand(L, curArg, c, side) || !ops->unfold(l, r, side)) { - c.constArgs.resize(savedSlots); + if (!readConstOperand(L, curArg, c, side, anchor, acceptsTensors) || + !addOwnedBuffers(ops, l, c, side) || + !ops->unfold(l, r, side)) { + dropSlotsAfter(c, savedBufs, savedTensors); + break; + } + + if (r.nodeCount() == 0) { + // A kernel is the whole expression, so it can only be a chain's sole step. + // chainRoot stays the arena's INPUT node, which is what extract() returns. + if (!r.kernel.fn || !c.rootAfterStep.empty()) { + dropSlotsAfter(c, savedBufs, savedTensors); + break; + } + c.singleStepKernel = r.kernel; + c.rootAfterStep.push_back(chainRoot); + c.layerIdx.push_back(j); break; } const int next = fusion::instantiate(arena_, chainRoot, r); if (next < 0 || fusion::detail::markLive(arena_.graph(), next, reachScratch_) > FUSION_MAX_EXPR_NODES) { - c.constArgs.resize(savedSlots); + dropSlotsAfter(c, savedBufs, savedTensors); break; } @@ -205,6 +309,9 @@ private: { const int nargs = (int)net_.args.size(); firstConsumerOf(prog(), nargs, firstConsumer_); + producerOf(prog(), nargs, producerOf_); + for (Arg out : graph_->outputs()) + externalArgs_.insert(out.idx); for (size_t i = 0; i < prog().size(); i++) { const Ptr& L = prog()[i]; @@ -222,7 +329,7 @@ private: ChainCandidate c; c.layerIdx.push_back((int)i); - growChain(i, c); + growChain(i, anchorOps->acceptsTensorOperands, c); if (c.rootAfterStep.empty()) continue; @@ -232,14 +339,11 @@ private: } } + //! Carries a kernel when there is no expression. The lone INPUT node is an identity, + //! so this is only ever built with a kernel attached. void freezeArena() { arenaPtr_ = arena_.sharedGraph(); - for (ChainCandidate& c : chains_) { - c.constBufs.reserve(c.constArgs.size()); - for (Arg a : c.constArgs) - c.constBufs.push_back(net_.argTensor(a)); - } } void fuseLongestChains() @@ -256,9 +360,20 @@ private: if (!sinkOps || !sinkOps->absorb) continue; + vector constBufs; + vector constBufPerChannel; + constBufs.reserve(c.constSlots.size()); + constBufPerChannel.reserve(c.constSlots.size()); + for (const ConstSlot& s : c.constSlots) { + constBufs.push_back(s.buf); + constBufPerChannel.push_back(s.perChannel); + } + size_t accepted = 0; + Ptr expr; for (size_t n = c.rootAfterStep.size(); n >= 1; n--) { - Ptr expr = fusion::extract(*arenaPtr_, c.rootAfterStep[n - 1], c.constBufs); + expr = fusion::extract(*arenaPtr_, c.rootAfterStep[n - 1], + constBufs, constBufPerChannel, c.tensorArgs); if (!expr) continue; if (n == 1) @@ -275,6 +390,11 @@ private: continue; } + // Wired on here rather than in absorb(), which the retry loop above may call + // more than once per chain. + for (Arg t : expr->tensorArgs) + anchorInfo->inputs.push_back(t); + anchorInfo->outputs[0] = prog()[c.layerIdx[accepted]]->outputs[0]; for (size_t k = 1; k <= accepted; k++) dropped_[c.layerIdx[k]] = true; @@ -307,7 +427,8 @@ private: AdjacencyGraphBuilder arena_; Ptr arenaPtr_; - vector firstConsumer_; + vector firstConsumer_, producerOf_; + std::set externalArgs_; vector claimed_, dropped_; vector chains_; vector reachScratch_; @@ -346,13 +467,35 @@ void Net::Impl::fuseChains() { if (!mainGraph) return; - // Sinks apply the fused math on the CPU path only; on an OpenCL target the - // absorbed layers would be dropped and their math never run. - if (IS_DNN_OPENCL_TARGET(preferableTarget)) - return; - vector usecounts; - useCounts(usecounts); - fuseChainsInGraph(*this, mainGraph, usecounts); + + // First: it deletes a layer, and if the chain pass absorbed the BatchNorm backwards into + // the preceding conv it would find nothing left. + fuseBN(); + + // Order is load-bearing: each pass matches shapes the one before it leaves. + fuseAttention(); + fuseMatMulConstBToGemm(); + fuseSharedInputGemm(); + fuseReshapeTranspose(); + fuseTransposeMatMul(); + fuseScaleSoftmax(); + + // A sink runs the math it absorbs in its own CPU kernel. setPreferableTarget resolves + // only CPU and CUDA while mainGraph is set, so nothing reaches here on OpenCL today. + if (!IS_DNN_OPENCL_TARGET(preferableTarget)) { + // Only a one-step chain carries the layer's kernel, so absorbing a step can + // expose a fusable next one. + vector usecounts; + for (int iter = 0; iter < 10; iter++) { + useCounts(usecounts); + if (!fuseChainsInGraph(*this, mainGraph, usecounts)) + break; + } + } + + // Leaves a whole layer behind rather than handing math to a sink, so unlike the + // chain pass it is not restricted to the CPU path. + fuseInstanceNormAffine(); } CV__DNN_INLINE_NS_END diff --git a/modules/dnn/src/layers/batch_norm2_layer.cpp b/modules/dnn/src/layers/batch_norm2_layer.cpp index 6cf8a8f8ad..1a28bc59cb 100644 --- a/modules/dnn/src/layers/batch_norm2_layer.cpp +++ b/modules/dnn/src/layers/batch_norm2_layer.cpp @@ -7,6 +7,7 @@ #include "../precomp.hpp" #include "layers_common.hpp" #include "../net_impl.hpp" +#include "../adjacency_graph.hpp" #include "../op_cuda.hpp" #ifdef HAVE_CUDA #include "../cuda4dnn/primitives/batch_norm.hpp" @@ -369,10 +370,46 @@ class BatchNorm2LayerImpl CV_FINAL : public BatchNorm2Layer { public: BatchNorm2LayerImpl(const LayerParams& params) { + registerFusionOpsOnce( + { &BatchNorm2LayerImpl::unfoldOp, nullptr, false, nullptr, + &BatchNorm2LayerImpl::ownedBuffersOp }); setParamsFrom(params); epsilon = params.get("epsilon", 1e-5); } + //! Only once freezeScaleBias() has run; before it the members are empty. + static bool ownedBuffersOp(const Layer* self, std::vector& out) + { + const BatchNorm2LayerImpl* l = static_cast(self); + if (l->inputs.size() != 1) + return false; + if (l->scale.empty() || l->bias.empty() || l->scale.total() != l->bias.total()) + return false; + if (l->scale.type() != CV_32F || l->bias.type() != CV_32F || + !l->scale.isContinuous() || !l->bias.isContinuous()) + return false; + out.push_back(l->scale); + out.push_back(l->bias); + return true; + } + + static bool unfoldOp(const Layer* self, LayerMath& r, const ConstOperand& side) + { + return static_cast(self)->unfoldMath(r, side); + } + + bool unfoldMath(LayerMath& r, const ConstOperand& side) const + { + if (side.count != 2 || !side.at(0).isBuffer() || !side.at(1).isBuffer()) + return false; + + const int s = r.perChannelConstant(side.at(0).bufferId); + const int scaled = r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, s); + const int b = r.perChannelConstant(side.at(1).bufferId); + r.binary(FusionEltwiseOp::ADD, scaled, b); + return true; + } + bool supportBackend(int backendId) CV_OVERRIDE { return backendId == DNN_BACKEND_OPENCV diff --git a/modules/dnn/src/layers/conv2_common.cpp b/modules/dnn/src/layers/conv2_common.cpp index 949f7edef1..c235bd9583 100644 --- a/modules/dnn/src/layers/conv2_common.cpp +++ b/modules/dnn/src/layers/conv2_common.cpp @@ -283,30 +283,18 @@ void repackConvWeights(const Mat& weights, Mat& Wpack, int outtype, int ngroups, Wpack.setZero(); parallel_for_(Range(0, K), [&](const Range& range) { - int Cg = wshape[1], Kg = K / ngroups; - int ksize = wpackShape[2], Kblk = wpackShape[1], C1Max = wpackShape[3]; - int C0 = C0_, K0 = C0; + const ConvWeightPack pack = ConvWeightPack::forConv(wshape, wpackShape, ngroups, C0_); + const int Cg = pack.Cg, ksize = pack.ksize; + const size_t tapStride = pack.tapStride(); const float* wdata = weights.ptr(); float* Wpackdata = Wpack.ptr(); for (int k = range.start; k < range.end; ++k) { - int g = k / Kg; - int kin = k - g * Kg; - int kblk = kin / K0; - int k0 = kin & (K0 - 1); - - int c_start = g * Cg; - int c00 = c_start & (C0 - 1); - for (int c = 0; c < Cg; ++c) { - int ch = c00 + c; - int c1 = ch / C0; - int c0 = ch & (C0 - 1); - - const float* wptr = wdata + ((k * Cg + c) * ksize); - float* wpackptr = Wpackdata + (((g * Kblk + kblk) * ksize * C1Max + c1) * C0 + c0)*K0 + k0; + const float* wptr = wdata + ((size_t)(k * Cg + c) * ksize); + float* wpackptr = Wpackdata + pack.offset(k, c); for (int i = 0; i < ksize; ++i) { - wpackptr[i*(C1Max*C0*K0)] = wptr[i]; + wpackptr[i*tapStride] = wptr[i]; } } } diff --git a/modules/dnn/src/layers/conv2_common.hpp b/modules/dnn/src/layers/conv2_common.hpp index 8564cae180..289c4f9a17 100644 --- a/modules/dnn/src/layers/conv2_common.hpp +++ b/modules/dnn/src/layers/conv2_common.hpp @@ -105,6 +105,44 @@ typedef void (*ConvFunc)(const void* inp, const void* residual, void* out, ConvFunc getConvFunc(int depth, int C0); ConvFunc getDepthwiseConvFunc(int depth); +/** @brief Where a weight lands in the (ngroups, Kblk, ksize, C1Max, C0*K0) packed buffer. + +repackConvWeights() writes through this and anything editing packed weights afterwards reads +through it, so the layout has one definition. Hands back element indices rather than typed +pointers, since the same layout carries int8. Integer math only: this header is compiled at +several CPU baselines. +*/ +struct ConvWeightPack +{ + int Kg, Cg, K0, Kblk, ksize, C1Max, C0; + + //! @p wshape0 is the plain (K, Cg, spatial...) filter. ConvTranspose swaps that + //! convention, so it needs its own factory rather than this one. + static ConvWeightPack forConv(const MatShape& wshape0, const MatShape& wpackShape, + int ngroups, int C0) + { + ConvWeightPack p; + p.Kg = wshape0[0]/ngroups; + p.Cg = wshape0[1]; + p.K0 = p.C0 = C0; + p.Kblk = wpackShape[1]; + p.ksize = wpackShape[2]; + p.C1Max = wpackShape[3]; + return p; + } + + size_t tapStride() const { return (size_t)C1Max*C0*K0; } + + //! Output channel @p k, input channel @p c within its group. Tap i adds i*tapStride(). + size_t offset(int k, int c) const + { + int g = k/Kg, kin = k - g*Kg; + int kblk = kin/K0, k0 = kin & (K0 - 1); + int ch = ((g*Cg) & (C0 - 1)) + c; + return ((((size_t)(g*Kblk + kblk)*ksize)*C1Max + ch/C0)*C0 + (ch & (C0 - 1)))*K0 + k0; + } +}; + void repackDepthwiseConvWeights(const Mat& weights, Mat& Wpack, int outtype, int C0); void repackConvWeights(const Mat& weights, Mat& Wpack, int outtype, int ngroups, int C0); diff --git a/modules/dnn/src/layers/conv2_layer.cpp b/modules/dnn/src/layers/conv2_layer.cpp index 3303dc660e..dd2f5d64e1 100644 --- a/modules/dnn/src/layers/conv2_layer.cpp +++ b/modules/dnn/src/layers/conv2_layer.cpp @@ -36,7 +36,8 @@ class Conv2LayerImpl : public Conv2Layer public: Conv2LayerImpl(const LayerParams& params) { - registerFusionOpsOnce({ nullptr, &Conv2LayerImpl::absorbOp }); + registerFusionOpsOnce({ nullptr, &Conv2LayerImpl::absorbOp, true, + &Conv2LayerImpl::foldInputScaleOp }); setParamsFrom(params); auto_pad = getAutoPadding(params); ceil_mode = params.get("ceil_mode", false); @@ -50,6 +51,116 @@ public: addResidual = false; } + static bool foldInputScaleOp(Layer* self, const Mat& scale, const Mat& shift) + { + return static_cast(self)->foldInputScale(scale, shift); + } + + //! conv(scale*x + shift) becomes conv'(x). Every weight copy the layer holds moves. + bool foldInputScale(const Mat& scale, const Mat& shift) + { + if (fusedBatchNorm || addResidual || fastActivation != FAST_ACTIV_NONE || + activationFunc != nullptr || !activ.empty()) + return false; + // The bias correction sums the whole kernel, so padding adds a spurious border + // shift. SAME_* carries its padding in auto_pad rather than in pads. + if (auto_pad != AUTO_PAD_NONE && auto_pad != AUTO_PAD_VALID) + return false; + for (int p : pads) + if (p > 0) + return false; + if (weights.empty() || weights.type() != CV_32F || wshape0.dims != 4 || packC0 <= 0) + return false; + if (scale.type() != CV_32F || shift.type() != CV_32F || + !scale.isContinuous() || !shift.isContinuous() || + scale.total() != shift.total()) + return false; + + const int K = wshape0[0], Cg = wshape0[1]; + if (ngroups <= 0 || K % ngroups != 0 || (int)scale.total() != Cg * ngroups) + return false; + // The loops below rewrite the weights in place, so nothing may fail after them. + if (!bias.empty() && (bias.type() != CV_32F || (int)bias.total() != K)) + return false; + + const float* sc = scale.ptr(); + const float* sh = shift.ptr(); + std::vector adj(K, 0.f); + const MatShape ws = weights.shape(); + float* W = weights.ptr(); + + // MLAS holds its own copy, packed from the plain matrix setWeights() then dropped. + // It arms only for 1x1 dense, so the fold below walks exactly those weights. + Mat plain; + if (!mlas_packed_B_.empty()) + plain.create(K, Cg, CV_32F); + + if (ngroups == K && Cg == 1) { + // depthwise: C1 x ksize x C0, and the input channel is the output channel + const int ksize = ws[1], C0 = ws[2]; + parallel_for_(Range(0, K), [&](const Range& r) { + for (int ch = r.start; ch < r.end; ch++) { + float* w = W + (size_t)(ch / C0) * ksize * C0 + (ch % C0); + float sw = 0.f; + for (int i = 0; i < ksize; i++) { + sw += w[(size_t)i * C0]; + w[(size_t)i * C0] *= sc[ch]; + } + adj[ch] += sh[ch] * sw; + } + }); + } else { + const ConvWeightPack pack = ConvWeightPack::forConv(wshape0, ws, ngroups, packC0); + const int ksize = pack.ksize; + const size_t sstride = pack.tapStride(); + parallel_for_(Range(0, K), [&](const Range& r) { + for (int k = r.start; k < r.end; k++) { + const int cbase = (k / pack.Kg) * Cg; // first input channel of k's group + for (int c = 0; c < Cg; c++) { + float* w = W + pack.offset(k, c); + float sw = 0.f; + for (int i = 0; i < ksize; i++) { + sw += w[i * sstride]; + w[i * sstride] *= sc[cbase + c]; + } + if (!plain.empty()) + plain.ptr(k)[c] = w[0]; // ksize == 1 whenever MLAS armed + adj[k] += sh[cbase + c] * sw; + } + } + }); + } + + if (!plain.empty() && + !mlasSgemmPackB(false, true, K, Cg, plain.ptr(), Cg, mlas_packed_B_.data)) + mlas_packed_B_.release(); + + // The CUDA path reads this plain copy instead of the packed one. + if (!origWeights.empty() && origWeights.type() == CV_32F) { + Mat w2d = origWeights.reshape(1, K); + const int Kg = K / ngroups, inner = (int)(origWeights.total() / ((size_t)K * Cg)); + parallel_for_(Range(0, K), [&](const Range& r) { + for (int k = r.start; k < r.end; k++) { + float* row = w2d.ptr(k); + for (int c = 0; c < Cg; c++) { + float* wc = row + (size_t)c * inner; + for (int i = 0; i < inner; i++) + wc[i] *= sc[(k / Kg) * Cg + c]; + } + } + }); + } + + if (bias.empty()) { + bias.fit(1, &K, CV_32F); + bias.setTo(0.f); + } + float* bp = bias.ptr(); + for (int k = 0; k < K; k++) + bp[k] += adj[k]; + return true; + } + virtual std::ostream& dumpAttrs(std::ostream& strm, int indent) const CV_OVERRIDE { prindent(strm, indent); @@ -133,6 +244,7 @@ public: int wtype = accuracy < 0 ? CV_32F : accuracy; wshape0 = weights_.shape(); + packC0 = C0; #ifdef HAVE_CUDA // Retain the original NCHW filter for the CUDA (cuDNN) path. weights_.convertTo(origWeights, CV_32F); @@ -186,48 +298,6 @@ public: } } - void fuseBatchNormWeights(const BatchNorm2Layer* bn) - { - Mat bn_scale, bn_bias; - bn->getScaleBias(bn_scale, bn_bias); - - CV_Assert(bn_scale.isContinuous() && bn_bias.isContinuous()); - CV_Assert(bn_scale.type() == CV_32F && bn_bias.type() == CV_32F); - CV_Assert(bn_scale.total() == bn_bias.total()); - int K = (int)bn_scale.total(); - CV_Assert(bias.empty() || (bias.type() == CV_32F && bias.total() == (size_t)K)); - const float* bias_data = bias.data ? bias.ptr() : nullptr; - - fusedScale.fit(1, &K, CV_32F); - fusedBias.fit(1, &K, CV_32F); - - const float* bn_scale_data = bn_scale.ptr(); - const float* bn_bias_data = bn_bias.ptr(); - float* fused_scale_data = fusedScale.ptr(); - float* fused_bias_data = fusedBias.ptr(); - - // (sum(x*w) + bias)*bn_scale + bn_bias => sum(x*w)*fused_scale + fused_bias, - // where fused_scale = bn_scale and fused_bias = bias*bn_scale + bn_bias. - for (size_t i = 0; i < K; i++) { - fused_scale_data[i] = bn_scale_data[i]; - fused_bias_data[i] = (bias_data ? bn_scale_data[i]*bias_data[i] : 0.f) + bn_bias_data[i]; - } - } - - virtual bool fuseBatchNorm(const Ptr& bnlayer) override - { - BatchNorm2Layer* bn = dynamic_cast(bnlayer.get()); - // addResidual means the graph order is conv->add->bn: the residual is added - // before BN, but the conv applies the fused BN scale only to conv(x), not to - // the residual. Refuse so BN stays separate and runs on (conv + residual). - if (fusedBatchNorm || !bn || bn->inputs.size() > 1 || - fastActivation != FAST_ACTIV_NONE || !activ.empty() || addResidual) - return false; - fuseBatchNormWeights(bn); - fusedBatchNorm = true; - return true; - } - virtual bool fuseAddBias(InputArray arr) CV_OVERRIDE { if (inputs.size() > 1 || fusedBatchNorm || addResidual) @@ -249,54 +319,6 @@ public: return true; } - virtual bool fuseActivation(const Ptr& activlayer) override - { - ActivationLayer* activ_ptr = dynamic_cast(activlayer.get()); - if (!activ_ptr || fastActivation != FAST_ACTIV_NONE || - activationFunc != nullptr || !activ.empty()) - return false; - - ReLULayer* activRelu = dynamic_cast(activ_ptr); - ReLU6Layer* activClip = dynamic_cast(activ_ptr); - ChannelsPReLULayer* activPRelu = dynamic_cast(activ_ptr); - if (activRelu) { - float alpha = activRelu->negativeSlope; - if (alpha == 0.f) { - fastActivation = FAST_ACTIV_RELU; - } else { - fastActivation = FAST_ACTIV_LEAKY_RELU; - activParams = {alpha}; - } - } else if (activClip && activClip->minValue == 0.f) { - fastActivation = FAST_ACTIV_CLIP; - activParams = {activClip->minValue, activClip->maxValue}; - } else if (activPRelu && activPRelu->blobs.size() == 1) { - fastActivation = FAST_ACTIV_PRELU; - const Mat& slopes = activPRelu->blobs[0]; - int slopesType = slopes.type(); - CV_Assert_N((slopesType == CV_32F || slopesType == CV_16F || slopesType == CV_16BF), - slopes.isContinuous()); - int nslopes = int(slopes.total()); - Mat(1, &nslopes, slopesType, (void*)slopes.data).convertTo(activParams, CV_32F); - } else { - activationFunc = activ_ptr->getActivationFunc(CV_32F, activParams); - if (!activationFunc) - return false; - } - return true; - } - - virtual bool fuseAddResidual(Arg residual) CV_OVERRIDE - { - if (activ.empty() && fastActivation == FAST_ACTIV_NONE && - activationFunc == nullptr && !addResidual && residual.idx >= 0) { - addResidual = true; - inputs.push_back(residual); - return true; - } - return false; - } - private: static bool splitConstOperand(const std::vector& nd, int node, int& other, int& bufId, float& scalarVal) @@ -322,6 +344,60 @@ private: return false; } + //! The operand of max(v, 0) or min(v, 0), or -1 when @p node is not that shape. + static int zeroClamped(const std::vector& nd, int node, FusionEltwiseOp op) + { + const FusionNode& n = nd[node]; + if (n.op != op || n.inputs.size() != 2) + return -1; + for (int k = 0; k < 2; k++) { + const FusionNode& z = nd[n.inputs[k]]; + if (z.op == FusionEltwiseOp::CONST && z.scalar == 0.f) + return n.inputs[1 - k]; + } + return -1; + } + + //! Matches max(x,0) + s*min(x,0). Interning sorts commutative operands, so both + //! sides of every node are tried. + static bool splitLeakyRelu(const std::vector& nd, int node, + int& operand, int& slopeNode) + { + const FusionNode& add = nd[node]; + if (add.op != FusionEltwiseOp::ADD || add.inputs.size() != 2) + return false; + + for (int s = 0; s < 2; s++) { + const FusionNode& mul = nd[add.inputs[1 - s]]; + if (mul.op != FusionEltwiseOp::MUL || mul.inputs.size() != 2) + continue; + const int x = zeroClamped(nd, add.inputs[s], FusionEltwiseOp::MAX); + if (x < 0) + continue; + for (int k = 0; k < 2; k++) { + if (zeroClamped(nd, mul.inputs[k], FusionEltwiseOp::MIN) != x) + continue; + operand = x; + slopeNode = mul.inputs[1 - k]; + return true; + } + } + return false; + } + + //! Splits one affine term off @p cur into @p out and steps past it. + bool splitAffineTerm(const std::vector& nd, const AdjacencyGraph& g, + int& cur, int K, std::vector& out) const + { + int other = -1, bufId = -1; + float sv = 0.f; + if (!splitConstOperand(nd, cur, other, bufId, sv) || + !readPerChannelValues(g, bufId, sv, K, out)) + return false; + cur = other; + return true; + } + bool readPerChannelValues(const AdjacencyGraph& g, int bufId, float scalarVal, int K, std::vector& out) const { @@ -335,15 +411,17 @@ private: if (c.empty() || c.type() != CV_32F || !c.isContinuous() || (int)c.total() != K) return false; - // Broadcasting puts the channel axis last-but-the-spatial-dims, so the - // constant is only per-channel if that axis holds K and the rest are 1. - const int nspatial = wshape0.dims - 2; - const int ax = c.dims - nspatial - 1; - if (ax < 0) - return false; - for (int d = 0; d < c.dims; d++) { - if (c.size[d] != (d == ax ? K : 1)) + // A declared buffer is per-channel by construction; a graph constant must prove it, + // since a bare [K] broadcasts onto the last axis, not the channel axis. + if (bufId >= (int)g.constBufPerChannel.size() || !g.constBufPerChannel[bufId]) { + const int nspatial = wshape0.dims - 2; + const int ax = c.dims - nspatial - 1; + if (ax < 0) return false; + for (int d = 0; d < c.dims; d++) { + if (c.size[d] != (d == ax ? K : 1)) + return false; + } } const float* p = c.ptr(); std::copy(p, p + K, out.begin()); @@ -356,7 +434,84 @@ public: return static_cast(self)->absorbMath(expr); } + //! The TENSOR side of a binary node, if it has one. Reports only; the caller commits. + static bool splitTensorOperand(const std::vector& nd, int node, + int& other, int& tensorId) + { + const FusionNode& n = nd[node]; + if (n.inputs.size() != 2) + return false; + for (int s = 0; s < 2; s++) { + if (nd[n.inputs[s]].op != FusionEltwiseOp::TENSOR) + continue; + tensorId = nd[n.inputs[s]].constBufferId; + other = n.inputs[1 - s]; + return true; + } + return false; + } + + //! Fills locals, not layer members: the match can still be refused after this. + bool splitActivation(const AdjacencyGraph& g, int node, int K, int& operand, + FastActivation& act, std::vector& ap) const + { + const std::vector& nd = g.nodes(); + if (nd[node].op == FusionEltwiseOp::CLAMP && nd[node].scalar == 0.f) { + act = FAST_ACTIV_CLIP; + ap.assign(2, 0.f); + ap[1] = nd[node].scalar2; + operand = nd[node].inputs[0]; + return true; + } + if (nd[node].op == FusionEltwiseOp::MAX && nd[node].inputs.size() == 2 && + nd[nd[node].inputs[1]].op == FusionEltwiseOp::CONST && + nd[nd[node].inputs[1]].scalar == 0.f) { + act = FAST_ACTIV_RELU; + operand = nd[node].inputs[0]; + return true; + } + int leakyOperand = -1, slopeNode = -1; + if (!splitLeakyRelu(nd, node, leakyOperand, slopeNode)) + return false; + const FusionNode& sl = nd[slopeNode]; + if (sl.op == FusionEltwiseOp::CONST) { + act = FAST_ACTIV_LEAKY_RELU; + ap.assign(1, sl.scalar); + operand = leakyOperand; + return true; + } + if (sl.op == FusionEltwiseOp::PER_CHANNEL_CONST) { + ap.assign(K, 0.f); + if (readPerChannelValues(g, sl.constBufferId, 0.f, K, ap)) { + act = FAST_ACTIV_PRELU; + operand = leakyOperand; + return true; + } + ap.clear(); + } + return false; + } + bool absorbMath(const Ptr& expr) + { + return absorbAffine(expr) || absorbKernel(expr); + } + + //! Takes an expression the layer has a kernel for. Only a one-layer chain carries + //! one, so this cannot swallow math absorbAffine() just turned down. + bool absorbKernel(const Ptr& expr) + { + if (!expr || !expr->kernel.fn || !expr->tensorArgs.empty()) + return false; + if (fastActivation != FAST_ACTIV_NONE || activationFunc != nullptr || !activ.empty()) + return false; + + activationFunc = expr->kernel.fn; + activParams.assign(expr->kernel.params, expr->kernel.params + expr->kernel.nparams); + return true; + } + + bool absorbAffine(const Ptr& expr) { if (!expr || expr->size() == 0) return false; @@ -371,7 +526,8 @@ public: return false; const int K = wshape0[0]; - if (!bias.empty() && (bias.dims != 1 || (int)bias.total() != K)) + // Only K contiguous floats are needed; the rank is the producer's business. + if (!bias.empty() && (!bias.isContinuous() || (int)bias.total() != K)) return false; int cur = expr->outputNode(); @@ -397,47 +553,54 @@ public: FastActivation act = FAST_ACTIV_NONE; std::vector ap; - if (nd[cur].op == FusionEltwiseOp::CLAMP && nd[cur].scalar == 0.f) { - act = FAST_ACTIV_CLIP; - ap.assign(2, 0.f); - ap[1] = nd[cur].scalar2; - cur = nd[cur].inputs[0]; - } else if (nd[cur].op == FusionEltwiseOp::MAX && nd[cur].inputs.size() == 2 && - nd[nd[cur].inputs[1]].op == FusionEltwiseOp::CONST && - nd[nd[cur].inputs[1]].scalar == 0.f) { - act = FAST_ACTIV_RELU; - cur = nd[cur].inputs[0]; - } + int activOperand = -1; + if (splitActivation(*expr, cur, K, activOperand, act, ap)) + cur = activOperand; if (act == FAST_ACTIV_CLIP) ap[1] *= postScale; + // The kernel adds the residual after the scale and bias and before the activation, + // so that is the only position it can occupy; a postScale would scale the sum too. + bool takesResidual = false; + if (nd[cur].op == FusionEltwiseOp::ADD) { + int other = -1, tensorId = -1; + if (splitTensorOperand(nd, cur, other, tensorId)) { + if (hasPostScale || tensorId != 0) + return false; + takesResidual = true; + cur = other; + } + } + // An unread tensor would still be wired on as an input, so refuse rather than ignore. + if (expr->tensorArgs.size() != (size_t)(takesResidual ? 1 : 0)) + return false; + std::vector scale(K, 1.f), shift(K, 0.f); bool affine = false; - if (nd[cur].op == FusionEltwiseOp::ADD) { - int other = -1, bufId = -1; - float sv = 0.f; - if (!splitConstOperand(nd, cur, other, bufId, sv)) + // A chain can stack more than one affine, so peel rounds until the input and + // compose them: x*a+b then *c+d is x*(a*c) + (b*c+d). + while (cur != 0) { + const int before = cur; + std::vector s(K, 1.f), t(K, 0.f); + + if (nd[cur].op == FusionEltwiseOp::ADD && + !splitAffineTerm(nd, *expr, cur, K, t)) return false; - if (!readPerChannelValues(*expr, bufId, sv, K, shift)) + if (nd[cur].op == FusionEltwiseOp::MUL && + !splitAffineTerm(nd, *expr, cur, K, s)) return false; + if (cur == before) + return false; + + for (int k = 0; k < K; k++) { + shift[k] += t[k]*scale[k]; // uses the old scale, so it goes first + scale[k] *= s[k]; + } affine = true; - cur = other; - } - if (nd[cur].op == FusionEltwiseOp::MUL) { - int other = -1, bufId = -1; - float sv = 0.f; - if (!splitConstOperand(nd, cur, other, bufId, sv)) - return false; - if (!readPerChannelValues(*expr, bufId, sv, K, scale)) - return false; - affine = true; - cur = other; } - if (cur != 0) - return false; - if (!affine && !hasPostScale && act == FAST_ACTIV_NONE) + if (!affine && !hasPostScale && act == FAST_ACTIV_NONE && !takesResidual) return false; if (affine || hasPostScale) { @@ -465,6 +628,7 @@ public: fastActivation = act; activParams = ap; } + addResidual = takesResidual; return true; } @@ -947,6 +1111,7 @@ public: Mat weights, bias, fusedScale, fusedBias; Mat origWeights; // original NCHW filter (FP32), kept for the CUDA path MatShape wshape0, prevInpshape; + int packC0 = 0; // block factor the weights were packed with ConvState cs; bool fusedBatchNorm; FastActivation fastActivation; diff --git a/modules/dnn/src/layers/cpu_kernels/fusion_apply.hpp b/modules/dnn/src/layers/cpu_kernels/fusion_apply.hpp index 33d7fa5933..dc537f3c62 100644 --- a/modules/dnn/src/layers/cpu_kernels/fusion_apply.hpp +++ b/modules/dnn/src/layers/cpu_kernels/fusion_apply.hpp @@ -67,6 +67,11 @@ inline bool PreparedFusion::take(const Ptr& e) continue; if (n.constBufferId < 0 || n.constBufferId >= (int)prepared.channelBufs.size()) return false; + // run() walks the last axis, but a flagged buffer varies along the channel one. + // Refusing lets the caller fall back to a chain that leaves it alone. + if (n.constBufferId < (int)e->constBufPerChannel.size() && + e->constBufPerChannel[n.constBufferId]) + return false; const Mat& m = e->constBufs[n.constBufferId]; if (m.dims < 1 || (int)m.total() != m.size[m.dims - 1]) return false; diff --git a/modules/dnn/src/layers/elementwise_layers.cpp b/modules/dnn/src/layers/elementwise_layers.cpp index d11d1c0c8b..8a68ba7484 100644 --- a/modules/dnn/src/layers/elementwise_layers.cpp +++ b/modules/dnn/src/layers/elementwise_layers.cpp @@ -426,10 +426,16 @@ public: bool unfoldMath(LayerMath& out, const ConstOperand& side) const { - if (!func.unfoldOp(out, side)) - return false; std::vector params; - if (ActivationFunc fn = func.getActivationFunc(CV_32F, params)) + ActivationFunc fn = func.getActivationFunc(CV_32F, params); + if (!func.unfoldOp(out, side)) { + // No expression, but a host that can run the kernel can still take it on. + if (!fn) + return false; + out.setKernel(fn, params); + return true; + } + if (fn) out.setKernel(fn, params); return true; } @@ -502,9 +508,14 @@ struct ReLUFunctor : public BaseFunctor bool unfoldOp(LayerMath& r, const ConstOperand&) const { - if (slope != 0.f) return false; const int zero = r.constant(0.f); - r.binary(FusionEltwiseOp::MAX, LayerMath::INPUT_VALUE, zero); + const int pos = r.binary(FusionEltwiseOp::MAX, LayerMath::INPUT_VALUE, zero); + if (slope == 0.f) + return true; + const int neg = r.binary(FusionEltwiseOp::MIN, LayerMath::INPUT_VALUE, zero); + const int s = r.constant(slope); + const int scaled = r.binary(FusionEltwiseOp::MUL, neg, s); + r.binary(FusionEltwiseOp::ADD, pos, scaled); return true; } @@ -1098,6 +1109,24 @@ struct GeluApproximationFunctor : public BaseDefaultFunctor return cv::dnn::getActivationFunc(ACTIV_SWISH); } + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + const int gate = fusion::detail::sigmoid(r); + r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, gate); + return true; + } + bool supportBackend(int backendId, int) { return backendId == DNN_BACKEND_OPENCV || @@ -1554,6 +1590,12 @@ struct ELUFunctor : public BaseDefaultFunctor return cv::dnn::getActivationFunc(ACTIV_ELU); } + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + fusion::detail::expLinearUnit(r, alpha, 1.f); + return true; + } + bool supportBackend(int backendId, int) { #ifdef HAVE_INF_ENGINE @@ -1644,6 +1686,12 @@ struct AbsValFunctor : public BaseDefaultFunctor { typedef AbsLayer Layer; + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + fusion::detail::abs(r, LayerMath::INPUT_VALUE); + return true; + } + bool supportBackend(int backendId, int) { #ifdef HAVE_INF_ENGINE @@ -2458,6 +2506,17 @@ struct HardSwishFunctor : public BaseDefaultFunctor return cv::dnn::getActivationFunc(ACTIV_HARDSWISH); } + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + const int sixth = r.constant(1.f / 6.f); + const int scaled = r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, sixth); + const int half = r.constant(0.5f); + const int biased = r.binary(FusionEltwiseOp::ADD, scaled, half); + const int gate = r.clamp(biased, 0.f, 1.f); + r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, gate); + return true; + } + bool supportBackend(int backendId, int) { return backendId == DNN_BACKEND_OPENCV || @@ -2697,6 +2756,16 @@ struct SoftsignFunctor : public BaseDefaultFunctor { typedef SoftsignLayer Layer; + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + const int magnitude = fusion::detail::abs(r, LayerMath::INPUT_VALUE); + const int one = r.constant(1.f); + const int denom = r.binary(FusionEltwiseOp::ADD, one, magnitude); + const int inv = r.unary(FusionEltwiseOp::RECIP, denom); + r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, inv); + return true; + } + bool supportBackend(int backendId, int) { return backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_CUDA; @@ -2789,6 +2858,15 @@ struct CeluFunctor : public BaseDefaultFunctor #endif } + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + // A negative alpha flips which side of zero the exponential term lands on. + if (!(alpha > 0.f)) + return false; + fusion::detail::expLinearUnit(r, alpha, 1.f / alpha); + return true; + } + bool supportBackend(int backendId, int) { return backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_CUDA; @@ -2856,6 +2934,16 @@ struct HardSigmoidFunctor : public BaseDefaultFunctor return cv::dnn::getActivationFunc(ACTIV_HARDSIGMOID); } + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + const int a = r.constant(alpha); + const int scaled = r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, a); + const int b = r.constant(beta); + const int biased = r.binary(FusionEltwiseOp::ADD, scaled, b); + r.clamp(biased, 0.f, 1.f); + return true; + } + bool supportBackend(int backendId, int) { return backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_CUDA; @@ -2903,6 +2991,14 @@ struct SeluFunctor : public BaseDefaultFunctor #endif } + bool unfoldOp(LayerMath& r, const ConstOperand&) const + { + const int elu = fusion::detail::expLinearUnit(r, alpha, 1.f); + const int g = r.constant(gamma); + r.binary(FusionEltwiseOp::MUL, elu, g); + return true; + } + bool supportBackend(int backendId, int) { return backendId == DNN_BACKEND_OPENCV || backendId == DNN_BACKEND_CUDA; @@ -3326,6 +3422,19 @@ const char* const ExpFunctor::BaseDefaultFunctor::ocl_kernel_name = struct ChannelsPReLUFunctor : public BaseFunctor { typedef ChannelsPReLULayer Layer; + + bool unfoldOp(LayerMath& r, const ConstOperand& side) const + { + if (side.count != 1 || !side.at(0).isBuffer()) + return false; + const int zero = r.constant(0.f); + const int pos = r.binary(FusionEltwiseOp::MAX, LayerMath::INPUT_VALUE, zero); + const int neg = r.binary(FusionEltwiseOp::MIN, LayerMath::INPUT_VALUE, zero); + const int slopes = r.perChannelConstant(side.at(0).bufferId); + const int scaled = r.binary(FusionEltwiseOp::MUL, neg, slopes); + r.binary(FusionEltwiseOp::ADD, pos, scaled); + return true; + } Mat scale; #ifdef HAVE_OPENCL UMat scale_umat; @@ -3476,6 +3585,10 @@ struct ChannelsPReLUFunctor : public BaseFunctor struct PReLUFunctor : public ChannelsPReLUFunctor { + //! The slope is per element here, which PER_CHANNEL_CONST cannot express; declining + //! keeps the inherited per-channel form from applying. + bool unfoldOp(LayerMath&, const ConstOperand&) const { return false; } + explicit PReLUFunctor(const Mat& scale_=Mat()) : ChannelsPReLUFunctor(scale_) { #ifdef HAVE_OPENCL @@ -3983,7 +4096,24 @@ Ptr ExpLayer::create(const LayerParams& params) class ChannelsPReLUImpl CV_FINAL : public ElementWiseLayer { public: - using ElementWiseLayer::ElementWiseLayer; + // fusionOpsFor() keys on the dynamic type, which the base constructor cannot register. + explicit ChannelsPReLUImpl(const ChannelsPReLUFunctor& f = ChannelsPReLUFunctor()) + : ElementWiseLayer(f) + { + registerFusionOpsOnce( + { &ElementWiseLayer::unfoldOp, nullptr, false, nullptr, + &ChannelsPReLUImpl::ownedBuffersOp }); + } + + //! setSlope() moved the slope into the functor, so it has no Arg for the pass to read. + static bool ownedBuffersOp(const Layer* self, std::vector& out) + { + const Mat& s = static_cast(self)->func.scale; + if (s.empty() || s.type() != CV_32F || !s.isContinuous()) + return false; + out.push_back(s); + return true; + } void setSlope(const Mat& slope) CV_OVERRIDE { diff --git a/modules/dnn/src/layers/nary_eltwise_layers.cpp b/modules/dnn/src/layers/nary_eltwise_layers.cpp index 16feb7d7f6..b291c309a9 100644 --- a/modules/dnn/src/layers/nary_eltwise_layers.cpp +++ b/modules/dnn/src/layers/nary_eltwise_layers.cpp @@ -212,6 +212,14 @@ public: } const FusionConst& k = side.at(0); + if (k.isTensor()) { + // Only a plain sum is order-independent enough for the host to place freely. + if (o != FusionEltwiseOp::ADD) + return false; + r.binary(o, LayerMath::INPUT_VALUE, r.tensorOperand(k.tensorId)); + return true; + } + if (o == FusionEltwiseOp::MAX && !k.isBuffer() && k.value == 0.f) r.setKernel(cv::dnn::getActivationFunc(ACTIV_RELU), { 0.f }); diff --git a/modules/dnn/src/net_impl.hpp b/modules/dnn/src/net_impl.hpp index 7599189cac..e36fd476ee 100644 --- a/modules/dnn/src/net_impl.hpp +++ b/modules/dnn/src/net_impl.hpp @@ -536,8 +536,8 @@ struct Net::Impl : public detail::NetImplBase void inferShapes(bool symbolic); // sets certain buffer index for each intermediate argument (Arg) void assignBuffers(); - // fuse batch norm, add bias and activation to convolution - void fuseBasic(); + // collapse Reshape+InstanceNorm+Reshape+Mul+Add into InstanceNorm or GroupNormalization + void fuseInstanceNormAffine(); void fuseChains(); // fuse ViT-style multi-head attention subgraphs void fuseAttention(); diff --git a/modules/dnn/src/net_impl2.cpp b/modules/dnn/src/net_impl2.cpp index 585ea32573..d5fa572f15 100644 --- a/modules/dnn/src/net_impl2.cpp +++ b/modules/dnn/src/net_impl2.cpp @@ -589,16 +589,8 @@ void Net::Impl::prepareForInference() widenHalfConstants(); fuseQDQ(); constFold(); - fuseBN(); constArgs(); - fuseAttention(); - fuseMatMulConstBToGemm(); - fuseSharedInputGemm(); - fuseReshapeTranspose(); - fuseTransposeMatMul(); - fuseScaleSoftmax(); fuseChains(); - fuseBasic(); totalLayers = updateGraphOfs(mainGraph, 0, true); prepared = true; } diff --git a/modules/dnn/test/test_fusion.cpp b/modules/dnn/test/test_fusion.cpp index 13e68f3289..aec556c0a8 100644 --- a/modules/dnn/test/test_fusion.cpp +++ b/modules/dnn/test/test_fusion.cpp @@ -5,6 +5,7 @@ // Third party copyrights are property of their respective owners. #include "test_precomp.hpp" +#include "npy_blob.hpp" #include "../src/adjacency_graph.hpp" #include "../src/layers/cpu_kernels/fusion_apply.hpp" @@ -151,6 +152,55 @@ TEST(Fusion, MathMatchesClosedForm) } } +TEST(Fusion, DeclaredMathMatchesTheActivation) +{ + const float kSqrt2Pi = 0.7978845834732056f; + const float kCoef = 0.044714998453855515f * kSqrt2Pi; + const float kSeluA = 1.67326319217681884765625f; + const float kSeluG = 1.05070102214813232421875f; + + const float xs[] = { -3.f, -0.5f, 0.f, 0.25f, 1.f, 4.f }; + for (float x : xs) { + struct { const char* type; float expected; } cases[] = { + { "Swish", x / (1.f + std::exp(-x)) }, + { "ELU", x >= 0.f ? x : std::exp(x) - 1.f }, + { "AbsVal", std::abs(x) }, + { "HardSwish", x * std::max(0.f, std::min(1.f, x / 6.f + 0.5f)) }, + { "Softsign", x / (1.f + std::abs(x)) }, + { "HardSigmoid", std::max(0.f, std::min(1.f, 0.2f * x + 0.5f)) }, + { "Celu", std::max(0.f, x) + std::min(0.f, std::expm1(x)) }, + { "Selu", kSeluG * (x > 0.f ? x : kSeluA * std::expm1(x)) }, + { "GeluApproximation", + 0.5f * x * (1.f + std::tanh(x * (kSqrt2Pi + kCoef * x * x))) }, + }; + + for (const auto& c : cases) { + LayerParams lp; + Ptr l = LayerFactory::createLayerInstance(c.type, lp); + ASSERT_TRUE(l) << c.type; + l->inputs.assign(1, Arg(1)); + + LayerMath m; + ConstOperand side; + ASSERT_TRUE(unfoldOf(l, m, side)) << c.type << " declared no math"; + EXPECT_NEAR(c.expected, eval1(m, x), 1e-5) << c.type << " at x=" << x; + } + } +} + +TEST(Fusion, CeluWithNegativeAlphaIsRefused) +{ + LayerParams lp; + lp.set("alpha", -1.f); + Ptr l = LayerFactory::createLayerInstance("Celu", lp); + ASSERT_TRUE(l); + l->inputs.assign(1, Arg(1)); + + LayerMath m; + ConstOperand side; + EXPECT_FALSE(unfoldOf(l, m, side)); +} + TEST(Fusion, EmptyMathIsRefused) { AdjacencyGraphBuilder arena; @@ -288,6 +338,33 @@ TEST(Fusion, NonElementwiseLayersDeclareToo) EXPECT_TRUE(nm.kernel.fn != nullptr) << "Max(x,0) declared no kernel"; } +TEST(Fusion, SubclassOfElementWiseLayerIsRegistered) +{ + LayerParams lp; + Mat slope(1, 4, CV_32F); + float* s = slope.ptr(); + s[0] = 0.1f; s[1] = 0.2f; s[2] = 0.3f; s[3] = 0.4f; + lp.blobs.push_back(slope); + + Ptr prelu = ChannelsPReLULayer::create(lp); + ASSERT_TRUE(prelu); + prelu->inputs.assign(1, Arg(1)); + + const FusionOps* ops = fusionOpsFor(prelu.get()); + ASSERT_TRUE(ops && ops->unfold) << "fusionOpsFor() missed the concrete type"; + + ASSERT_TRUE(ops->ownedBuffers); + std::vector owned; + ASSERT_TRUE(ops->ownedBuffers(prelu.get(), owned)); + ASSERT_EQ(1u, owned.size()); + + LayerMath m; + ConstOperand side; + side.count = 1; + side.consts[0].bufferId = 0; + ASSERT_TRUE(ops->unfold(prelu.get(), m, side)); +} + TEST(Fusion, ApplyTakesKernelPathThenInterpreterPath) { LayerMath r; @@ -371,6 +448,34 @@ TEST(Fusion, PerChannelConstIndexesTheLastAxis) EXPECT_FLOAT_EQ(want[i], y.ptr()[i]) << "i=" << i; } +TEST(Fusion, PerChannelBufferIsRefusedByTheInterpreter) +{ + AdjacencyGraphBuilder arena; + const int in = arena.internNode(FusionEltwiseOp::INPUT, {}); + LayerMath r; + r.binary(FusionEltwiseOp::MUL, LayerMath::INPUT_VALUE, r.perChannelConstant(0)); + const int root = fusion::instantiate(arena, in, r); + ASSERT_GE(root, 0); + + int three = 3; + Mat b(1, &three, CV_32F); + b.ptr()[0] = 2.f; + b.ptr()[1] = 3.f; + b.ptr()[2] = 4.f; + const std::vector bufs(1, b); + + Ptr lastAxis = fusion::extract(arena.graph(), root, bufs); + ASSERT_TRUE(lastAxis); + PreparedFusion plain; + EXPECT_TRUE(plain.take(lastAxis)); + + Ptr perChannel = + fusion::extract(arena.graph(), root, bufs, std::vector(1, 1)); + ASSERT_TRUE(perChannel); + PreparedFusion channel; + EXPECT_FALSE(channel.take(perChannel)); +} + TEST(Fusion, SharedRootKeepsEachChainsOwnBuffers) { AdjacencyGraphBuilder arena; @@ -456,4 +561,78 @@ TEST(Fusion, ShapeOfUnpinnedInputStaysDynamic) EXPECT_EQ(MatShape({1, 24, 2}), out.shape()); } +//! How many layers of @p type the fused program still holds. +static int fusedCount(Net& net, const char* type) +{ + Ptr g = net.getMainGraph(); + CV_Assert(g); + int n = 0; + for (const Ptr& l : g->prog()) + n += l && l->type == type; + return n; +} + +TEST(Fusion, ConvTakesTheResidualAdd) +{ + const std::string model = findDataFile("dnn/onnx/models/depthwiseconv_add.onnx"); + Net net = readNetFromONNX(model, ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + const int shape[] = {1, 8, 32, 32}; + Mat input(4, shape, CV_32F, Scalar(1.f)); + net.setInput(input); + net.forward(); + + EXPECT_EQ(fusedCount(net, "NaryEltwise"), 1) << "the residual Add was not absorbed"; +} + +TEST(Fusion, SharedProjectionsCollapseToOneGemm) +{ + const std::string model = + findDataFile("dnn/onnx/models/attention_shared_shape_reshape.onnx"); + Net net = readNetFromONNX(model, ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + const int shape[] = {1, 4, 8}; + Mat input(3, shape, CV_32F, Scalar(1.f)); + net.setInput(input); + net.forward(); + + EXPECT_EQ(fusedCount(net, "Gemm"), 1); + EXPECT_EQ(fusedCount(net, "Slice2"), 3); +} + +static void checkBatchNormFoldsIntoConv(const std::string& name) +{ + Net net = readNetFromONNX(findDataFile("dnn/onnx/models/" + name + ".onnx"), ENGINE_OPENCV); + ASSERT_TRUE(net.getMainGraph()); + + net.setInput(blobFromNPY(findDataFile("dnn/onnx/data/input_" + name + ".npy"))); + Mat out = net.forward(); + + EXPECT_EQ(0, fusedCount(net, "BatchNorm2")) << name << ": the fold did not fire"; + normAssert(blobFromNPY(findDataFile("dnn/onnx/data/output_" + name + ".npy")), out, + name.c_str()); +} + +TEST(Fusion, BatchNormFoldsIntoDenseConv) +{ + checkBatchNormFoldsIntoConv("batchnorm_conv_dense"); +} + +TEST(Fusion, BatchNormFoldsIntoDepthwiseConv) +{ + checkBatchNormFoldsIntoConv("batchnorm_conv_depthwise"); +} + +TEST(Fusion, BatchNormFoldsIntoGroupedConv) +{ + checkBatchNormFoldsIntoConv("batchnorm_conv_grouped"); +} + +TEST(Fusion, BatchNormFoldsIntoPrepacked1x1Conv) +{ + checkBatchNormFoldsIntoConv("batchnorm_conv_1x1_mlas"); +} + }} // namespace opencv_test